14

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

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

So that if I type:

export MY_VERSION="2010.4"

pluginRequires will be set at "2010.4", even if MY_VERSION is set to something else at run time.

UPDATE: (feb 21) Thanks for your help everyone. It works. As I'm using Rake as a build system, each of my CFLAGS is a ruby variable. Also the values need to end up in quotes. Therefore the gcc command line for me needs to look like this:

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

Which means this is in my Rakefile:

"-D\"PLUGIN_VERSION=\\\"#{ENV['MY_VERSION']}\\\"\""
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Julian Mann
  • 6,256
  • 5
  • 31
  • 43
  • 4
    This is not something the preprocessor will do. This is something your build system would have to do. – GManNickG Feb 19 '10 at 21:49

2 Answers2

21

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

i.e.:

$ gcc file.c -o file -D"THE_VERSION_STRING=${THE_VERSION_STRING}"
Seth
  • 45,033
  • 10
  • 85
  • 120
  • 1
    Shouldn't that be `-DTHE_VERSION_STRING="$(THE_VERSION_STRING)"`? – bk1e Feb 19 '10 at 21:57
  • 1
    @bk1e Yeah, I think you're right -- the docs actually show it as `-D name=definition` though, so maybe it doesn't matter. – Seth Feb 19 '10 at 22:03
  • @bk1e: not parenthesis - braces would work but are not necessary. – Jonathan Leffler Feb 19 '10 at 22:56
  • Sorry, the space wasn't the point of my comment, the quotes were. `sh` eats double quotes unless you escape them with backslashes, and `make` preserves double quotes. `export FOO="bar"` is valid for both `make` and `sh` derivatives, so it's unclear whether the environment variable's value contains double quotes. If it doesn't, then you need to add double quotes when you use `-D`, and adding them before the macro name won't work--you need a C string literal to the right of the `=` sign. Also, `make` uses parens and `sh` uses braces. – bk1e Feb 20 '10 at 02:56
  • And hey, I just noticed the `$` indicating that you were assuming `sh` not `make`. Also, I forgot that `make` invokes commands in rules via a subshell, so you still need to use backslashes with `make`. – bk1e Feb 20 '10 at 03:04
1

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 can't do it like this. The only way to extract environment variables is at runtime with the getenv() function. You will need to explicitly extract the value and copy it to pluginRequires.

If you want the effect of a compile-time constant, then you'll have to specify the definition on the compiler commandline as Seth suggests.

Community
  • 1
  • 1
greyfade
  • 24,948
  • 7
  • 64
  • 80