Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading