C++ Best practices for constants

后端 未结 6 1158
难免孤独
难免孤独 2020-12-09 16:15

I have a whole bunch of constants that I want access to in different parts of my code, but that I want to have easy access to as a whole:

static const bool d         


        
6条回答
  •  情歌与酒
    2020-12-09 16:45

    What is the problem with this usage?
    Do not declare a static type in header file, It does not do what you think it does.

    When you declare a static in header file a copy of that variable gets created in each Translation Unit(TU) where you include that header file, SO each TU sees a different variable, this is opposite to your expectation of having a global.

    Suggested Solution:
    You should declare them as extern in a header file and define them in exactly one cpp file while include the header with extern in every cpp file where you want to access them.

    Good Read:
    How should i use extern?

提交回复
热议问题