0

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?

hackjutsu
  • 8,336
  • 13
  • 47
  • 87
  • 2
    Did you formally `export ANDROID_HOME` (or `export ANDROID_HOME=/the/value/of/android/home`)? If not, you created a shell variable, not an environment variable. If you run the command `env | grep ANDROID_HOME`, what do you see? – Jonathan Leffler May 18 '15 at 00:29
  • Yes, I formally `export ANDROID_HOME` and get the correct value when running `env | grep ANDROID_HOME` . I ran the codes in the Xcode... Maybe Xcode was using a different environment. – hackjutsu May 18 '15 at 00:47

1 Answers1

6

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
Michaelangel007
  • 2,798
  • 1
  • 25
  • 23
jksoegaard
  • 901
  • 1
  • 12
  • 21
  • Thanks! Your instructions work. My project was created as an Xcode project. Does Xcode use a different environment? – hackjutsu May 18 '15 at 00:40
  • 4
    Yes, apps started from the Finder or Dock are not subprocesses of the shell. `.bash_profile` is only used when initializing login shells like those you get in Terminal. They don't affect GUI apps or their subprocesses. You can build a program using Xcode, but you would have to run it from a shell for it to inherit environment variables set by the shell. Xcode allows you to specify environment variables to be used when running a program in Product > Scheme > Edit Scheme > Run in the sidebar > Arguments tab. – Ken Thomases May 18 '15 at 00:47
  • Awesome! Thank you for the insightful explanation. – hackjutsu May 18 '15 at 00:57