Search code examples
c++constants

Can C++ compile-time constants have a different value for each compiled binary?


Say my entire repo relies on a compile-time constant:

// consts.h
constexpr int MAGIC_CONST = 10;

Then I can use it in my main function:

// main.cpp
int main(int argc, char** argv) {
  // use MAGIC_CONST to do something:
  double data[MAGIC_CONST];
}

Now, say I want to compile several "instances" of this main: main_1.cpp, main_2.cpp, ..., each with a different MAGIC_CONST. How do I do this? Because MAGIC_CONST is defined in the header and is unique for the entire codebase and not per-binary.

I've also (clumsily) tried using extern const like this:

// consts.h
extern const int MAGIC_CONST; // declaration only

Then define its actual value in each main:

// main_0.cpp
extern const int MAGIC_CONST = 10;

int main(int argc, char** argv) {
  double data[MAGIC_CONST];
}

This won't work either since extern const is not a compile-time constant.

I've also thought about old-style #defines but I actually need to use my MAGIC_CONST elsewhere in the codebase too and not just in main_0.cpp.

Any help appreciated!


Solution

  • You can make use of variable template as shown below:

    header.h

    #pragma once
    template<int i> constexpr int variable = i;
    

    main.cpp

    #include "header.h"
    
    int main()
    {
      constexpr int j = variable<10> ;//works   
    }
    

    source.cpp

    #include "header.h"
    
    constexpr int k = variable<11>;
    

    Demo