Can I define an environment variable and use it in conditional compilation?
Asked Answered
P

1

10

I know that I can do this in a *.h file:

#ifdef _DEBUG
#pragma comment(lib, "libtiffd.lib")
#else
#pragma comment(lib, "libtiff.lib")
#endif

But I want a way that I can do something such as this:

#ifdef V2.4.6
#ifdef _DEBUG
#pragma comment(lib, "opencv_calib3d246d.lib")
#else
#pragma comment(lib, "opencv_calib3d246.lib")
#endif
#else
#ifdef _DEBUG
#pragma comment(lib, "opencv_calib3d249d.lib")
#else
#pragma comment(lib, "opencv_calib3d249.lib")
#endif
#endif

and V2.4.6 be an environment variable. Can I do this?

I don't want to define V2.4.6 inside Visual Studio or code as it would be different on different systems.

Progeny answered 7/8, 2014 at 13:41 Comment(8)
AFAIK this isn't possible in code alone - you'll need some sort of custom pre-build rule that can read environment vars and translate them into macro definitions.Benjie
@DrewMcGowen as you know, we can use environment variables inside a make file, so it should be possible to do the same in visual studio as I think VS uses some kind of make (I think it is using nmake)Progeny
I'm pretty sure you're not allowed dots in macro names.Thetis
@Thetis thanks for that. But it is not the main point. The varable could be names as V_2_4_6.Progeny
@mans: Visual Studio uses the MSBuild build system, certainly not nmake.Transoceanic
@Transoceanic You are right, but how different is it from NMake? Can I convert a NMake project into a MSBuild project? If yes, then it should be able to support environment variable for conditional compilation.Progeny
As far as I can tell, the environment is available in the form of predefined macros in the project files. From there, you can add their value to the PreprocessorDefinitions with something like <PreprocessorDefinitions>VERSION=$(whatever);%(PreprocessorDefinitions)</PreprocessorDefinitions>.Lubeck
You can also use conditionals in the project files (and includes, if you have several projects). You may have to edit the project files manually to get at all of the possibilities.Lubeck
A
12

My test: Create environment variable MY_VERSION = V2_4_6. Start VS, in project properties, C++, Preprocessor, Preprocessor Definitions, add $(MY_VERSION). This program:

#ifdef V2_4_6
    cout << "OK" << endl;
#else
    cout << "??" << endl;
#endif

prints "OK". Exit Visual Studio, change MY_VERSION value to another value or remove it. Start VS, rebuild the program. Now it prints "??".

Note that after changing the variable value it is neccesary to restart Visual Studio (since environment variables are not refreshed dynamically), and make Rebuild All.

Angeliaangelic answered 7/8, 2014 at 14:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.