Okay to declare static global variable in .h file?

后端 未结 6 2007
野趣味
野趣味 2020-12-13 07:36

static keyword keeps the scope of a global variable limited to that translation unit. If I use static int x in a .h file and include that .h file every

6条回答
  •  佛祖请我去吃肉
    2020-12-13 08:03

    If you write

    static const int x
    

    in an .h file then every translation unit that #include-s this .h will have its own private variable x.

    If you want to have 1 global variable visible to everyone you should write

    extern const int x;
    

    in the .h file and

    const int x = ...;
    

    in one of the .cpp files.

    If you want to have a static const int visible to just one translation unit - don't mention it in the .h files at all.

提交回复
热议问题