0

Does the preprocessor have a mechanism to access environment variables directly as defines, without the need to define them on the command line?

For instance,

SOME_VAR=foo gcc code.c

and

#if ENV_SOME_VAR == "foo"
#define SOME_VAR_IS_FOO
#endif
Qix - MONICA WAS MISTREATED
  • 14,451
  • 16
  • 82
  • 145
  • possible duplicate of [how do I use c preprocessor to make a substitution with an environment variable](http://stackoverflow.com/questions/2299824/how-do-i-use-c-preprocessor-to-make-a-substitution-with-an-environment-variable) – Thom Wiggers Mar 31 '15 at 20:40
  • 2
    No, the standard C preprocessor has no such mechanism, and I'm not aware of any compiler extensions that provide such a feature either. However, build systems do this all the time, including Cmake and GNU Autotools. A simple shell script would do this as well, though all of these mean you'd need to test the environment variable to determine whether to define `ENV_SOME_VAR`, in which case, why not just define it using something like `-DENV_SOME_VAR="${SOME_VAR:-unfoo}"`, which would define `ENV_SOME_VAR` in your C file as the value of `$SOME_VAR` if it's set or "unfoo" if it's empty or unset. –  Mar 31 '15 at 20:48
  • @ThomWiggers no, similar, but not the same. – Qix - MONICA WAS MISTREATED Mar 31 '15 at 21:00
  • @ChronoKitsune could you post as an answer? – Qix - MONICA WAS MISTREATED Mar 31 '15 at 21:01

1 Answers1

2

No, the standard C preprocessor has no such mechanism, and I'm not aware of any compiler extensions that provide such a feature either.

However, you can do this using a build system, such as Cmake or GNU Autoconf, the latter being a part of the GNU Autotools build system. A simple shell script would do this as well, though all of these options mean you'd need to test the environment variable to determine whether to define ENV_SOME_VAR, in which case, you might just define it using something like the following:

-DENV_SOME_VAR="${SOME_VAR:-unfoo}"

That would define ENV_SOME_VAR in your C file as the value of $SOME_VAR if it's set or to the string "unfoo" if $SOME_VAR is empty (null) or unset.