0

I've come across this stack overflow answer which suggests two ways of handling static string class members: https://stackoverflow.com/a/1563906

Defining in cpp file

// a.h
class A {   
private:      
  static const string RECTANGLE;
};
// a.cpp
const string A::RECTANGLE = "rectangle";

Inlining

// a.h
class A {   
private:      
  inline static const string RECTANGLE = "rectangle";
};

I've tried the inline approach and noticed the string is duplicated in every translation unit which imported the header file, and the executable has multiple duplicates.

So, why would anyone prefer the inlining approach if it increases the executable size?

Test setup I've used:

// a.h
#pragma once
class A {
    public:
        void f();
};

// a.cpp
#include <iostream>
#include "a.h"
#include "b.h" // for no reason

void A::f() {
    std::cout << "A" << std::endl;
}

// b.h
#pragma once
#include <string>
class B {
    public:
        void f();
    private:
        inline static const std::string STR = "JOHNWICK";
};

// b.cpp
#include <iostream>
#include "b.h"

void B::f() {
    std::cout << "B" << std::endl;
}

// main.cpp
#include <iostream>
#include "a.h"
#include "b.h"

int main() {
    A a;
    B b;
    a.f();
    b.f();
    return 0;
}

Compile: g++ main.cpp a.cpp b.cpp

strings a.out | grep "JOHNWICK"

prints JOHNWICK <3 times>

  • https://stackoverflow.com/questions/5010216/constant-combining-in-optimizing-compilers – KamilCuk Jan 22 '23 at 11:07
  • Why? For example because they do not want to have cpp files in their module and hope that users use their module with -fmerge-constants option. – Öö Tiib Jan 22 '23 at 11:09
  • you have to turn on compiler optimziations if you care about quality of the compilers output. Default settings for compilers are usually as little optimizations as possible, also because having the program follow the code closely helps for debugging – 463035818_is_not_an_ai Jan 22 '23 at 11:16

0 Answers0