关于 OSX 上的 getenv()
About getenv() on OSX
我需要获取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
我需要获取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