关于OSX上的getenv()

About getenv() on OSX

本文关键字:getenv 上的 OSX 关于      更新时间:2023-10-16

我需要获得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()。要么这样,要么。当调用getenv()时,bash_profile不生效。

我错过了什么?

你的代码看起来是正确的-所以你很可能在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