dbrembilla
dbrembilla

Reputation: 157

Generate #include macro from environment variable

as you say, it works.

But can I build -in some way- the string for the include directive ? Something like

in .login

setenv REPO "/tmp"

compile

# gcc -D"REPO=${REPO}" source.c

in source.c

#ifdef REPO
    #include ${REPO}/my_dir/my_file.h 
#endif

thanks

Upvotes: 1

Views: 1351

Answers (1)

tucuxi
tucuxi

Reputation: 17945

As Joachim writes, in GCC you can use the -D flag to #define things from the command-line:

gcc -DTEST source.c

// in source.c
#include <stdio.h>
int main() {
  #ifdef TEST
  printf("TEST macro is #defined!\n"); // only runs if -DTEST
  #endif
  return 0;
}

You can easily plug in environment variables (at compile-time) via this mechanism:

gcc "-DTEST=$MY_ENV_VAR" source.c

If you need to use the run-time value of the environment variable, then the macro preprocessor (#define, #ifdef, ...) can't help you. Use getenv() instead, and forget about macros.

More to the point:

#include TEST
int main() {
    printf("Hello world!\n");
    return 0;
}

Will work fine only if compiled with "-DTEST=<stdio.h>" (note the quotes).

Upvotes: 3

Related Questions