是否可以直接从 C 源代码传递 GCC 参数?

Is it possible to pass GCC arguments directly from C source code?

我希望能够从我的 C 源代码向 GCC 传递参数,类似这样...

// pass the "-ggdb" argument to GCC (I know this won't work!)
#define GCC_DEBUG_ARG -ggdb
int main(void) {
    return 0;
}

使用这段代码,我想简单地 运行 gcc myfile.c 这实际上 运行 gcc myfile.c -ggdb (因为“-ggdb”参数已从C 源代码)。

我对 makeCFLAGS 环境变量一起使用不感兴趣,我只想知道是否可以在 C 中嵌入 GCC 选项源代码

你想做的事一般情况下是做不到的

但是,最近的 GCC(例如 GCC 8 in end of 2018) accepts many options and some of them could be passed by function attributes or by function specific pragmas(但是,他们不接受 -g 但确实接受 -O2)。

此外,您可以在每次编译中使用 -g(使用 GCC,它可以与 -O2 等优化标志混合使用;因此 运行时间性能不会受到影响。当然 -g 会增加编译时间和生成的目标文件的大小)。请注意(在 Linux 上)DWARF 调试信息在生成的汇编程序文件中可见(例如,尝试使用 gcc -Wall -g -O -S -fverbose-asm foo.c 编译 foo.c,查看生成的 foo.s,并通过删除 -g)

重复

I'd like to simply run gcc myfile.c

这是一个非常坏的习惯。在继续编写程序之前,您应该 运行 gcc -Wall -Wextra -g myfile.c -o myprog 获取所有警告(您 确实 想要它们)并在 executable myprog. Read How to debug small programs 中调试信息。

I'm not interested in using make with the CFLAGS environment variable

但是你真的应该Using make or some other build automation tool (e.g. ninja, omake, rake,等等,等等....) ,在实践中,使用GCC的常规方式.

或者,在 Linux 上写一个小 shell script doing the compilation (this is particularly worthwhile if your program is a single source file; for anything bigger, you really should use some build automation tool). At last, if you use emacs as your source code editor, you could add a few lines of comments (like at end of my manydl.c example) specifying Emacs file variables to tune the compilation(由 emacs 完成)

如果这些约定让您感到惊讶,请阅读 Unix philosophy then study -for inspiration- the source code of some existing free software (e.g. on github, gitlab 或您最喜欢的 Linux 发行版)。

最后,GCC itself is a free software project (but a huge one of more than five millions lines of mostly C++ source code). So you can improve it the way you desire (if you follow its GPLv3+ license),在不知何故研究了它的源代码之后。这将花费您数月(或数年)的工作时间(因为 GCC 理解起来非常复杂)。

另请参阅 this answer 相关问题。

你也可以(但我建议不要这样做,因为它很混乱)用你的 PATH variable and have some directory there -e.g. $HOME/bin/, ahead of /usr/bin/ which contains /usr/bin/gcc, with your shell script named gcc; but don't do that, you'll be confused. Instead write some "generic" mygcc shell script 玩把戏 运行 /usr/bin/gcc 并向它添加适当的标志(我相信这是不值得的努力)。