C-从标头到外壳的定义/const值

  • 本文关键字:定义 const 外壳 c shell
  • 更新时间 :
  • 英文 :


假设一个标头,如果通常编写某些C程序,则将包含-I/path/header.h。它有一堆#defines,其中一些是"复合",例如#define SOMECONST SOME_PREPROC_FUNC(3)和一些枚举。

希望在一行中获得SOME_CONSTSOME_ENUM值的值是什么?不编写编译自定义可执行文件。伪事物是行不通的,但希望可以说明这一点:

./$(cc '#include <header>n#include <stdio>nvoid main () {printf("%dn", $const_or_enum_name);}' -I/path/header.h)

或使用其他工具?

您可以执行预处理器步骤并在此之后停止。可以使用cc -E

完成
$ cat header.h
#define VAR 3
$ echo -e "#include "header.h"nVAR" | cc -E -xc -
<lots of stuff>
3
$ echo -e "#include "header.h"nVAR" | cc -E -xc - | tail -1
3

这实际上告诉ccstdin上运行预处理器,将结果打印为stdout。需要-xc来指定语言实际上是c。

稍微高级的示例:

$ cat header.h 
#define VAR1 3
#define VAR2 5
#define VAR3 VAR1*VAR2
$ echo -e "#include "header.h"nVAR3" | cc -E -xc - | tail -1 | bc
15

最新更新