Search code examples
c++c++11constantsexternconstexpr

'Constexpr' vs 'extern const'. Which has priority?


When to use constexpr and when to use extern const?

I have a situation like:

  • in header (.h):

    extern const int MAX_NUMBER_OF_ROWS;
    
  • in source (.cpp):

    const int MAX_NUMBER_OF_ROWS= 99;
    

The files (header and source) contains just such definitions and declarations.

Is it recommanded to use just the constexpr in the header file and get rid of the source file, like in here?:

// this is in the header file. There is no cpp file any more.
constexpr int MAX_NUMBER_OF_ROWS= 99;

Solution

  • Using extern const in the header file only tells the compiler that the variable exists and that it is not modifiable. It doesn't tell the compiler its value which means it's not a compile-time constant anymore. If it's not a compile-time constant then it can't be used for e.g. case or as an array size.

    As said by M.M in the comment, either use

    const int MAX_NUMBER_OF_ROWS= 99;
    

    or

    constexpr int MAX_NUMBER_OF_ROWS= 99;
    

    directly in the header file and it will be a compile-time constant in all translation units that include the header file.