Krzysztof Stanisławek
Krzysztof Stanisławek

Reputation: 1277

Setting static constant value (not by preprocessor) at compile time

just short question. I can define preprocessor variables at compile time, using -D flag for g++. But is there a way to set value of normal constant variable this way?

I want to avoid preprocessor. I don't see any reason, why this couldn't be possible.

Upvotes: 2

Views: 1965

Answers (3)

liori
liori

Reputation: 42337

Well, you cannot define a variable from a compiler switch. You can fake it though:

const int my_cli_defined_variable = MY_CLI_DEFINED_VARIABLE
#undef MY_CLI_DEFINED_VARIABLE

and then:

g++ -DMY_CLI_DEFINED_VARIABLE=5 …

The second line will make sure that the preprocessor macro won't be used by accident by your real code, because the macro won't exist anymore. So, the only way to use this CLI-defined variable will be in a type-safe way through the const variable.

A full example that takes care of the situation when the macro is not defined:

const int my_cli_defined_variable = 
#ifdef MY_CLI_DEFINED_VARIABLE
    MY_CLI_DEFINED_VARIABLE;
#undef MY_CLI_DEFINED_VARIABLE
#else
    42;
#endif

Upvotes: 7

jterrace
jterrace

Reputation: 67083

You could do something like this:

#include <iostream>

#if defined MYCONST_VAL
static const int MYCONST = MYCONST_VAL;
#else
static const int MYCONST = 3;
#endif

int main(int argc, char** argv) {
  std::cout << MYCONST << std::endl;
  return 0;
}

This works:

$ clang++ preproc.cc 
$ ./a.out 
3
$ clang++ -D MYCONST_VAL=77 preproc.cc 
$ ./a.out 
77

It's somewhat ugly though. I wouldn't recommend doing this.

Upvotes: 3

celtschk
celtschk

Reputation: 19731

If you have only a small set of values (or if you don't mind having a ton of small files), you can write a set of header files containing the variable definition with appropriate initializer, and then include the wanted one using the -include option.

However note that when including files, no matter whether using #include in the source code or using the -include option of g++, you also use the preprocessor, so you'll not be able to avoid that.

For example, you might have a header file 8bit.h containing the line

int const bit_size = 8;

and another header file 16bit.h containing the line

int const bit_size = 16;

and then compile your source with

g++ foo.cc -include 8bit.h

Upvotes: 1

Related Questions