c++macosgetenv

About getenv() on OSX


I need to get the value of the environment variable ANDROID_HOME on OSX (set in .bash_profile). I can verify its existence by typing echo $ANDROID_HOME in the terminal.

Here is the code: (Xcode project)

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 output is always The ANDROID_HOME is NOT set.. I don't think I'm using getenv() correctly here. Either that, or .bash_profile is not in effect when the getenv() is called.

What am I missing?


Solution

  • Your code seems correct - so you're most probably calling your program in an environment where ANDROID_HOME is indeed not set. How are you starting your program?

    I changed your source code to actually be compilable, and it works fine on my OS X system:

    #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");
    }
    

    Compile that with:

    g++ getenv.cpp -o getenv
    

    Now run:

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