non-integral constants

前端 未结 5 1651
-上瘾入骨i
-上瘾入骨i 2020-12-28 08:39

I want a header file with a non-integral constant in it, e.g. a class. Note the constant does not need to be a compile-time constant.

stati         


        
5条回答
  •  旧时难觅i
    2020-12-28 09:23

    You seem to have them mixed up.

    You are right about

    static const std::string Ten = "10"; 
    

    version. It will "work", but it will create a separate object in each translation unit.

    The version without static will have the same effect. It won't produce linker errors, but will define a separate object in each translation unit. In C++ language const objects have internal linkage by default, meaning that

    const std::string Ten = "10"; // `static` is optional
    

    is exactly equivalent to the previous version with static.

    The version with extern and initializer

    extern const std::string Ten = "10"; // it's a definition!
    

    will produce a definition of an object with external linkage (it is a definition because of the presence of an initializer). This version will result in linker errors, since you'll end up with multiple definitions of an object with external linkage - a violation of ODR.

    Here's how you can do it:

    In order to achieve what you are trying to achieve, you have to declare your constant in the header file

    extern const std::string Ten; // non-defining declaration
    

    and then define it (with initializer) in one and only one of the implementation files

    extern const std::string Ten = "10"; // definition, `extern` optional
    

    (If the constant is pre-declared as extern, then extern in the definition is optional. Even without an explicit extern it will define a const object with external linkage.)

提交回复
热议问题