从头到shell获取define / const值?

时间:2017-04-18 19:38:43

标签: c shell

假设一个人有一些标题,那么通常会写一些C程序,其中包含-I/path/header.h。它有一堆#defines其中一些是"复合物"比如#define SOMECONST SOME_PREPROC_FUNC(3)以及一些枚举。

有希望将SOME_CONSTSOME_ENUM的值设为shell的好方法是什么?无需编写自定义可执行文件。假的东西不起作用,但希望能说明这一点:

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

或者可能使用其他工具?

1 个答案:

答案 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

这实际上告诉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