How do I use the C preprocessor to make a substitution with an environment variable

半城伤御伤魂 提交于 2019-11-30 09:14:57

问题


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']}\\\"\""

回答1:


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}"



回答2:


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.



来源:https://stackoverflow.com/questions/2299824/how-do-i-use-the-c-preprocessor-to-make-a-substitution-with-an-environment-varia

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!