[英]Using constexpr together with getenv (or alternative)
I'm trying to capture environment variables from a build server as compile time constants that can be used within the build library. 我正在尝试从构建服务器捕获环境变量作为可在构建库中使用的编译时间常数。 I have a static class that can be queried for these constants and would like to use
constexpr
with std::getenv
, but I get the errors that constexpr variable must be initialised from a constant expression due to the fact that getenv
returns a non-const char*
, due to the fact it is a little long in the tooth . 我有一个可以查询这些常量的静态类,并且想将
constexpr
与std::getenv
一起使用,但是由于getenv
返回非常量这一事实,我得到了必须从常量表达式初始化constexpr变量的错误。 char*
,因为它有点长 。
I'd like to avoid bloating the build scripts by injecting all of the env vars as -DMY_ENV_VAR
if possible. 我想通过将所有env var注入为
-DMY_ENV_VAR
来避免过大的构建脚本。 If the answer is simply "no, you must add each as a definition like that", and there are no modern alternatives to getenv
or tricks I can use then so be it, but then there are 2 spots to maintain, which is not ideal. 如果答案是简单的“不,您必须将每个都添加为这样的定义”,并且没有现代替代方法可以使用
getenv
或技巧,那就可以了,但是要保留两个位置,这并不理想。
The runtime environment of a C++ program, which getenv
interacts with, is fundamentally not compile-time constant. 与
getenv
交互的C ++程序的运行时环境基本上不是编译时常量。
The char*
vs const char*
issue you pointed out has nothing to do with this problem. 您指出的
char*
vs const char*
问题与该问题无关。
Compile-time constants are things that are fixed at compile-time. 编译时常量是在编译时固定的东西。 Your runtime environment is not fixed at compile-time.
您的运行时环境在编译时并不固定。 So
getenv
's return values cannot be constexpr
. 因此,
getenv
的返回值不能为constexpr
。
You could create script that writes a header containing the build-time environment variables you want to store in constexpr
storage, instead of a pile of -D
commands. 您可以创建脚本来写一个标头,该标头包含要存储在
constexpr
存储中的构建时环境变量,而不是一堆-D
命令。
I don't think std::getenv can be used as a constexpr since it's a runtime system call. 我不认为std :: getenv可以用作constexpr,因为它是运行时系统调用。 What do you mean by "there would be 2 spots to maintain"?
您所说的“要维护两个点”是什么意思? Your static class would just use the defines passed into build, ie
您的静态类将只使用传递给构建的定义,即
class CBuildConsts
{
public:
static const std::string Thing;
}
and then in the .cpp file 然后在.cpp文件中
const std::string CBuildConsts::Thing = std::string("MY_ENV_VAR");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.