关于OSX上的getenv()

hac*_*tsu 0 c++ macos getenv

我需要获取ANDROID_HOMEOSX上环境变量的值(在.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");
}
Run Code Online (Sandbox Code Playgroud)

输出始终为The ANDROID_HOME is NOT set.。我认为我在getenv()这里使用不正确。要么,否则.bash_profilegetenv()调用时无效。

我想念什么?

jks*_*ard 5

您的代码似乎正确-因此,您很可能在确实未设置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");
}
Run Code Online (Sandbox Code Playgroud)

用以下命令编译:

g++ getenv.cpp -o getenv
Run Code Online (Sandbox Code Playgroud)

现在运行:

./getenv
The ANDROID_HOME is NOT set.

export ANDROID_HOME=something
./getenv
The ANDROID_HOME is: something
Run Code Online (Sandbox Code Playgroud)

  • 是的,从Finder或Dock启动的应用程序不是Shell的子进程。`.bash_profile`仅在初始化登录shell(如您在Terminal中获得的登录shell)时使用。它们不会影响GUI应用程序或其子流程。您可以使用Xcode来构建程序,但是必须从Shell运行该程序才能使其继承该Shell设置的环境变量。Xcode允许您在侧边栏&gt;参数选项卡中的产品&gt;方案&gt;编辑方案&gt;运行中指定运行程序时要使用的环境变量。 (3认同)