3

I want to detect an environment variable outside of Xcode's settings. I can do this at runtime checking the environment like specified in Detecting if iOS app is run in debugger, but is there a way to do it with a preprocessor macro like this?

#ifdef USER_GRADHA
    // do some stuff
#else
    // do other stuff
#endif

My environment variable is set, but it is not reaching the compilation phase of the .m files. I want to accomplish this without having to modify the project's preprocessor macro variable, because I want compilation to be different for each user without them having to modify it.

Community
  • 1
  • 1
Grzegorz Adam Hankiewicz
  • 7,349
  • 1
  • 36
  • 78

2 Answers2

2

No. Compilation is very intentionally a deterministic process and does not depend on the outside environment. The only way I know of for compilation to differ based on who's compiling is via the Source Trees preference in Xcode, and that's explicitly intended for users to keep source trees in different locations on different machines but have the build setting be the same (because it can refer to the source tree location set in the preferences).

Lily Ballard
  • 182,031
  • 33
  • 381
  • 347
1

First, don't forget getenv to read an environment variable into a string, if you can get away with using a plain string instead of a preprocessor variable. E.g.,

#include <stdlib.h>
char *ug = getenv("USER_GRADHA");
if (ug) {
  //use the environment variable here
} else {
  //it's NULL == undefined env variable (in all likelihood)
}

If you need to have a preprocessor variable, the shell can set one at compiler invocation using the POSIX-standard -D or -U flag. Unfortunately, the simple

gcc -DUSER_GRADHA=$USER_GRADHA file.c

is likely to cause you trouble, because if the environment variable is undefined, you'll have a blank but defined preprocessor variable. So it may be easiest to use a shell conditional, like

if [ $USER_GRADHA ] ; then ug="-D$USER_GADHA"; else ug="-U$USER_GRADHA"; fi
c99 $ug file.c

This is easy to implement in a makefile or many other sorts of hooks to execute arbitrary shell code for compilation.

Finally, there's always Autotools, which is designed for exactly this problem of compiling based on information about the environment. You asked about Xcode, so Autotools may not fit your workflow (and a lot of people don't understand Autotools and dismiss it out of hand), but it's there if you want it.

bk.
  • 6,068
  • 2
  • 24
  • 28