我有一个包含大量C文件的目录.对于这些C文件中的每一个,我都需要添加该行#include config.h.有没有办法避免手动这样做?
我想也许有一种简洁的方法告诉预处理器这样做,或者可能将一个构造良好的标志传递给链接器.如何让目录中的所有文件"包含"相同的头文件?
要么使用-include开关
$ cat foo.c
int main(void) {
printf("%s\n", "ohai there o/");
return 0;
}
$ gcc -include stdio.h foo.c
Run Code Online (Sandbox Code Playgroud)
或者编写一个脚本,自动为您插入包含的内容
在这些示例中编辑.c文件,并在文件的第1行添加包含.
假设bash shell,GNU sed:
while read -r; do
sed -i '1i #include "config.h"' "$REPLY"
done < <(find /path/to/project/dir -type f -name "*.c")
Run Code Online (Sandbox Code Playgroud)
或者用POSIX
find /path/to/project/dir -type f -name "*.c" | while read -r file; do
ed "$file" <<EOF
0a
#include "config.h"
.
wq
EOF
done
Run Code Online (Sandbox Code Playgroud)