假设一个人有一些标题,那么通常会写一些C程序,其中包含-I/path/header.h
。它有一堆#defines
其中一些是"复合物"比如#define SOMECONST SOME_PREPROC_FUNC(3)
以及一些枚举。
有希望将SOME_CONST
和SOME_ENUM
的值设为shell的好方法是什么?无需编写自定义可执行文件。假的东西不起作用,但希望能说明这一点:
./$(cc '#include <header>\n#include <stdio>\nvoid main () {printf("%d\n", $const_or_enum_name);}' -I/path/header.h)
或者可能使用其他工具?
答案 0 :(得分:2)
您可以执行预处理器步骤并在此之后停止。这可以使用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
这实际上告诉cc
在stdin
上运行预处理器,将结果打印到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