c++ - 关于 OSX 上的 getenv()

标签 c++ macos getenv

我需要在 OSX 上获取环境变量 ANDROID_HOME 的值(在 .bash_profile 中设置)。我可以通过在终端中输入 echo $ANDROID_HOME 来验证它的存在。

这是代码:(Xcode 项目)

void testGetEnv(const string envName) {

    char* pEnv;
    pEnv = getenv(envName.c_str());
    if (pEnv!=NULL) {
        cout<< "The " << envName << " is: " << pEnv << endl;
    } else {
        cout<< "The " << envName << " is NOT set."<< endl;
    }
}

int main() {
    testGetEnv("ANDROID_HOME");
}

输出总是The ANDROID_HOME is NOT set.。我认为我在这里没有正确使用 getenv()。或者 .bash_profile 在调用 getenv() 时无效。

我错过了什么?

最佳答案

您的代码似乎是正确的 - 因此您很可能在确实未设置 ANDROID_HOME 的环境中调用您的程序。你是如何开始你的计划的?

我将您的源代码更改为实际上是可编译的,它在我的 OS X 系统上运行良好:

#include <iostream>
#include <string>
#include <stdlib.h>

using namespace std;

void testGetEnv(const string envName) {

  char* pEnv;
  pEnv = getenv(envName.c_str());
  if (pEnv!=NULL) {
    cout<< "The " << envName << " is: " << pEnv << endl;
  } else {
    cout<< "The " << envName << " is NOT set."<< endl;
  }
}

int main() {
  testGetEnv("ANDROID_HOME");
}

编译:

g++ getenv.cpp -o getenv

现在运行:

./getenv
The ANDROID_HOME is NOT set.

export ANDROID_HOME=something
./getenv
The ANDROID_HOME is: something

关于c++ - 关于 OSX 上的 getenv(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30293487/

相关文章:

c++ - 为什么我收到一个简单的 boost 生产者/消费者程序的锁定断言失败?

macos - 使用 Intellij IDEA 重新加载远程 Spring Boot 应用程序的异常

c - 带 -m32 选项的 32 位 gcc 和 64 位 gcc 有什么区别?

使用 getenv 调用 CreateProcessAsUser 的 C++ LPTSTR 问题

c - 在C中获取系统环境变量

java - 来自 Docker 容器的 AWS DynamoDb 的连接问题

c++ - 不能用 boost beast 做 https 请求

c++ - 匹配字符串长度;查找和替换;在 C++ 中删除 HTML 标签

objective-c - 如果我想编写一个 iPad 应用程序,我必须购买 iPad 吗?

java - 使用 Java 让 getenv 在 Windows 中工作