将 constexpr 与 getenv (或替代方案)一起使用

Using constexpr together with getenv (or alternative)

我正在尝试从构建服务器捕获环境变量作为编译时常量,以便在构建库中使用。我有一个可以查询这些常量的静态 class 并且想将 constexprstd::getenv 一起使用,但是我得到了必须从常量表达式初始化 constexpr 变量的错误,因为getenv returns 一个非常量 char* 的事实,因为它是 .

如果可能的话,我想通过将所有环境变量注入 -DMY_ENV_VAR 来避免使构建脚本膨胀。如果答案只是 "no, you must add each as a definition like that",并且没有 getenv 的现代替代品或我可以使用的技巧,那么就这样吧,但是有 2 个位置需要维护,这并不理想。

getenv 交互的 C++ 程序的运行时环境根本上不是 compile-time 常量。

您指出的 char* vs const char* 问题与此问题无关。

Compile-time常量是固定在compile-time的东西。您的运行时环境未固定在 compile-time。所以 getenv 的 return 值 不能 constexpr.

您可以创建一个脚本来编写 header,其中包含要存储在 constexpr 存储中的 build-time 环境变量,而不是一堆 -D 命令。

我认为 std::getenv 不能用作 constexpr,因为它是运行时系统调用。 "there would be 2 spots to maintain" 是什么意思?您的静态 class 只会使用传递到构建中的定义,即

class CBuildConsts
{
    public:
    static const std::string Thing;
}

然后在 .cpp 文件中

const std::string CBuildConsts::Thing = std::string("MY_ENV_VAR");