0

我需要ANDROID_HOME在 OSX 上获取环境变量的值(在.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_profilegetenv()在被调用时无效。

我错过了什么?

4

1 回答 1

6

您的代码似乎是正确的-因此您很可能在确实未设置 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
于 2015-05-18T00:33:03.927 回答