const variables in header file and static initialization fiasco

后端 未结 4 1897
情歌与酒
情歌与酒 2021-02-02 16:42

After reading a lot of the questions regarding initialization of static variables I am still not sure how this applies to const variables at namespace level.

<
4条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-02 17:05

    Your first definition places path1 in each compilation unit that includes config.h. To avoid this, don't define variables in header files. Usually you'd declare the variables in the header as extern:

    extern const std::string path1;
    extern const MyClass myclass1;
    

    and define them in a translation unit, e.g. config.cpp:

    const std::string path1 = "/xyz/abc";
    const MyClass myclass1("test");
    

    Sometimes you need a constant variable that is usable only from one translation unit. Then you can declare that variable at file scope as static.

    static const std::string path1 = "/xyz/abc";
    

    static is not deprecated any more. static and extern are sometimes implied, but I always forget where and how, so I usually specify them explicitly for all namespace-level variables.

提交回复
热议问题