Share via


how to us the value of an environment variable during compile time in c++

Question

Thursday, May 15, 2014 4:55 PM

I have an environment variable with a string value. I want to use this value in my c++ project as a constant. The environment variable gets created in the prebuild step and I want the value to get assigned to a variable during the compile time. Is there any way to do it. I tried defining add it to the additional options in the c++ command prompt visual studio, as below

/DENV_VAR=$(ENV_VAR)

and defining it in a header file as

#define W(X)            L## #X           
#define W_CHAR(X)    W(X)        
#define W_ENV    W_CHAR(ENV_VAR)

But it throws me error during build saying the L and # are illegal. Is there any other way to do this?

All replies (2)

Friday, May 16, 2014 2:27 PM âś…Answered | 1 vote

I think he's talking about a compile-time variable.

@lv_2014
Your solution was almost correct, but you have to use %% to query an environment variable.
The $() syntax is used to expand msbuild variables.

In the C/C++ > Preprocessor > Preprocessor Directives, add this to the list of symbols, separated with a semicolon:

    ENV_VAR=%ENV_VAR%;....

Note that you cannot set ENV_VAR in one of the build steps because each build step is executed in a new cmd process. So any changes to the environment are not propagated. You'll have to set the contents of ENV_VAR before starting Visual Studio.

What you can also do is to create a tiny header in the pre-build step, e.g. using

    echo #define ENV_VAR  "My Favorite String" > SymbolDefinition.h

and #include that in your sources. However, this will keep your project out-of-date all the time. But you can use fc and a bit batch script logic to avoid the recreation of SymbolDefinition.h if that is not necessary.


Friday, May 16, 2014 8:08 AM

Hi,

According to your description, you need to use an environment variable in your C++ project as a constant.

Please refer to http://social.msdn.microsoft.com/Forums/en-US/ac16d801-dd65-4983-940a-78bc2bd77d36/how-is-an-environment-variable-read-using-visualc-?forum=vcgeneral

Use getenv. You can also add a third argument, char *envp[], to the main function.

So you can get the environment variable in your program, then you can use it as what you like.

And the sample code snippet

wchar_t environmentBuffer[10000];
GetEnvironmentVariable(L"<<your env. variable>>",
    _countof(environmentBuffer));

wcout << environmentBuffer << endl;

(coming from http://social.msdn.microsoft.com/Forums/en-US/e8cebf14-c541-44d7-86e8-9a03205372ff/how-to-get-environment-variable-value-by-c?forum=vclanguage)

Best regards,