Defining global constant in C++

前端 未结 10 1894
梦如初夏
梦如初夏 2020-11-29 16:44

I want to define a constant in C++ to be visible in several source files. I can imagine the following ways to define it in a header file:

  1. #define GLOBAL_
相关标签:
10条回答
  • 2020-11-29 17:24

    To answer your second question:

    (2) is illegal because it violates the One Definition Rule. It defines GLOBAL_CONST_VAR in every file where it's included, i.e. more than once. (5) is legal because it's not subject to the One Definition Rule. Each GLOBAL_CONST_VAR is a separate definition, local to that file where it's included. All those definitions share the same name and value of course, but their addresses could differ.

    0 讨论(0)
  • 2020-11-29 17:25

    If you use C++11 or later, try using compile-time constants:

    constexpr int GLOBAL_CONST_VAR{ 0xff };
    
    0 讨论(0)
  • 2020-11-29 17:29

    (5) says exactly what you want to say. Plus it lets the compiler optimize it away most of the time. (6) on the other hand won't let the compiler ever optimize it away because the compiler doesn't know if you'll change it eventually or not.

    0 讨论(0)
  • 2020-11-29 17:30

    If it's going to be a constant then you should mark it as a constant - that's why 2 is bad in my opinion.

    The compiler can use the const nature of the value to expand some of the maths, and indeed other operations that use the value.

    The choice between 5 and 6 - hmm; 5 just feels better to me.

    In 6) the value is unnecessarily detached from it's declaration.

    I typically would have one or more of these headers that only defines constants etc within them, and then no other 'clever' stuff - nice lightweight headers that can easily be included anywhere.

    0 讨论(0)
提交回复
热议问题