【问题标题】:C++ Program through CLion cannot find environment variableC++程序通过CLion找不到环境变量
【发布时间】:2024-04-29 23:25:02
【问题描述】:

我正在尝试在 CLion 中编写一个 C++ 程序并使用一个自定义环境变量。操作系统是 Ubuntu 16.04

假设环境变量是 $test。

int main (int argc, char **argv){

    std::cout<<getenv("PATH");
    std::cout<<getenv("test");
}

我已经在setting->build...->CMAKE->Environment中设置了环境变量 environment variable set

我可以在通过 CMAKE 构建时打印它。

message($ENV{test}) 

this is test

但是当编译并运行上面的编译代码时,只有 $PATH 被打印出来。程序似乎找不到 $test 变量。

有人知道如何解决这个问题吗?

【问题讨论】:

  • 通常 IDE 允许在不同的环境中构建和运行您的程序。在“运行配置”中设置环境变量,而不是在 CMake 选项中。
  • @yeputons 谢谢!在“运行配置”中设置环境变量后它可以工作
  • CMake环境变量相关问题:*.com/a/38874446/1052261

标签: c++ cmake environment-variables clion


【解决方案1】:

如果你想在 C++ 运行时读取环境变量,例如使用std::getenv

您可以在“运行配置”中添加此类变量(重要不是 CMake 环境变量)

然后在你的代码中:

std::filesystem::path getRootConfigPath()
{
    // std::getenv can return nullptr and this is why we CAN'T assign it directly to std::string
    const char* path = std::getenv("TEST_CONFIG_DIR");
    gcpp::exception::fail_if_true(
        path == nullptr, WHERE_IN_FILE, "No such environment variable: ${TEST_CONFIG_DIR}");

    gcpp::exception::fail_if_true(std::string_view{path}.empty(),
                                  WHERE_IN_FILE,
                                  "Missing ${TEST_CONFIG_DIR} environment variable");

    const std::filesystem::path testConfigDir{path};
    gcpp::exception::fail_if_false(std::filesystem::exists(testConfigDir) &&
                                       std::filesystem::is_directory(testConfigDir),
                                   WHERE_IN_FILE,
                                   "Invalid ${TEST_CONFIG_DIR} dir:" + testConfigDir.string());
    return testConfigDir;
}

gcpp::exception::fail_if_true的来源


在运行单元测试时以更友好的方式执行此操作的其他方法是将此变量添加到模板。

所以每当您点击:

这样的变量已经存在了。

【讨论】:

    【解决方案2】:

    我遇到了同样的问题,以下步骤解决了我的问题。 在

    中设置变量

    运行->编辑配置、应用程序/环境变量

    【讨论】:

      【解决方案3】:

      好吧,我不知道 CLion,但看起来你设置的环境变量只在 CMake 中使用。当你运行你的程序时,它根本就没有设置。

      【讨论】:

      • 是的!就像@yeputons 所说,在运行配置中设置环境变量后,它就可以工作了!非常感谢!