matthewrdev
matthewrdev

Reputation: 12190

Use environment variable as compile time constant in C++

As part of a build process, I need to take an environment variable defined by a batch script and use it as a constant within the code at compile time.

For example, say I have defined an environment variable named BUILD_VERSION and set it to 1.0.0, when compiled I want 1.0.0 to be baked into my code. EG:

Batch file:

set BUILD_VERSION = 1.0.0
; call vs compiler

C++ File:

const std::string build_version = BUILD_VERSION // Which will result in "1.0.0".

How would I go about doing this?

Upvotes: 10

Views: 11937

Answers (3)

matthewrdev
matthewrdev

Reputation: 12190

In the end I followed txchelp advice and added a /D flag into the Command Line -> Additional Options section of the project properties to declare the environment variable as a preprocessor definition.

It looked something like this:

enter image description here

Then in the batch script that started the build:

set SVN_BUILD_VERSION=1.0.0

And finally to extract it as a string within the source code:

#define STRINGIZER(arg)     #arg
#define STR_VALUE(arg)      STRINGIZER(arg)
#define BUILD_VERSION_STRING STR_VALUE(BUILD_VERSION)

// ...

const std::string version = BUILD_VERSION_STRING; // Results in "1.0.0".

Upvotes: 10

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145359

A VERSION_INFO resource could be a good way go.

The version info so embedded can be inspected by right-clicking the executable and checking its properties.

To do that at the command line:

  • Redirect output from a batch file to an [.rc] file defining the resource.

  • Compile the resource using rc.exe.

  • Embed the resulting .res file by simply passing it to the linker.

Within Visual Studio it might be more complicated.

Upvotes: 0

Spock77
Spock77

Reputation: 3325

You can use a prebuild step (I suppose you are on Visual Studio) which will run script which will get this environment variable value, parse C++ source file and change the value "1.0.0.0" to "1.0.0.1".

Such substitution can be conveniently done by awk.

Upvotes: 0

Related Questions