How to use C preprocessor to do environment variable replacement

In the code below, I would like the value of THE_VERSION_STRING taken from the value of the environment variable MY_VERSION at compile time

 namespace myPluginStrings { const char* pluginVendor = "me"; const char* pluginRequires = THE_VERSION_STRING; }; 

So if I print:

 export MY_VERSION="2010.4" 

pluginRequires will be set to "2010.4" even if MY_VERSION is set to something else at runtime.

UPDATE: (feb 21) Thanks for all your help. It works. Since I use Rake as a build system, each of my CFLAGS is a ruby ​​variable. Values ​​must also end with quotation marks. So for the gcc command line, I need to look like this:

 gcc file.c -o file -D"PLUGIN_VERSION=\"6.5\"" 

What does this mean in my rakefile:

 "-D\"PLUGIN_VERSION=\\\"#{ENV['MY_VERSION']}\\\"\"" 
+6
c ++ c-preprocessor environment-variables substitution
source share
2 answers

If I remember correctly, you can use the -D command-line option with gcc to the #define value at compile time.

ie:

 $ gcc file.c -o file -D"THE_VERSION_STRING=${THE_VERSION_STRING}" 
+13
source share

In the code below, I would like the value of THE_VERSION_STRING to be taken from the value of the environment variable MY_VERSION at compile time

No, you cannot do it like this. The only way to extract environment variables is at run time using the getenv() function. You will need to explicitly extract the value and copy it to pluginRequires .

If you need the effect of a compile-time constant, you will need to specify a definition on the compiler command line, as Seth suggests.

0
source share

All Articles