从环境变量生成#include宏

时间:2021-02-04 00:58:14

as you say, it works.

正如你所说,它有效。

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

但我可以用某种方式构建 - include指令的字符串吗?就像是

in .login

在.login中

setenv REPO "/tmp"

compile

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

in source.c

在source.c中

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

thanks

谢谢

1 个解决方案

#1


2  

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

正如Joachim所写,在GCC中,您可以使用-D标志来从命令行中定义#define:

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.

如果需要使用环境变量的运行时值,那么宏预处理器(#define,#ifde,...)无法帮助您。请改用getenv(),忘掉宏。

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).

只有在使用“-DTEST = ”编译时才能正常工作(注意引号)。

#1


2  

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

正如Joachim所写,在GCC中,您可以使用-D标志来从命令行中定义#define:

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.

如果需要使用环境变量的运行时值,那么宏预处理器(#define,#ifde,...)无法帮助您。请改用getenv(),忘掉宏。

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).

只有在使用“-DTEST = ”编译时才能正常工作(注意引号)。