简体   繁体   English

在C ++中使用环境变量作为编译时常量

[英]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. 例如,假设我已经定义了一个名为BUILD_VERSION的环境变量并将BUILD_VERSION设置为1.0.0 ,在编译时我希望将1.0.0烘焙到我的代码中。 EG: 例如:

Batch file: 批处理文件:

set BUILD_VERSION = 1.0.0
; call vs compiler

C++ File: C ++文件:

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

How would I go about doing this? 我该怎么做呢?

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. 最后,我遵循了txchelp建议,并在项目属性的命令行 - >附加选项部分添加了一个/D标志,以将环境变量声明为预处理器定义。

It looked something like this: 它看起来像这样:

在此输入图像描述

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

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". 您可以使用预构建步骤(我假设您在Visual Studio上)将运行脚本,该脚本将获取此环境变量值,解析C ++源文件并将值“1.0.0.0”更改为“1.0.0.1”。

Such substitution can be conveniently done by awk . 这种替换可以通过awk方便地完成。

A VERSION_INFO resource could be a good way go. VERSION_INFO资源可能是一个好方法。

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. 将批处理文件的输出重定向到定义资源的[.rc]文件。

  • Compile the resource using rc.exe . 使用rc.exe编译资源。

  • Embed the resulting .res file by simply passing it to the linker. 只需将结果传递给链接器即可嵌入生成的.res文件。

Within Visual Studio it might be more complicated. 在Visual Studio中,它可能更复杂。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM