从 C/C++ 内部访问 GCC 编译器开关程序
是否可以访问从程序内部编译的 gcc 编译器开关 ac/c++ 程序?
在我的应用程序中,作为日志信息的一部分,我想编写程序编译时使用的开关,例如编译器的优化和预处理器变量输入。
It is possible to access the gcc compiler switches a c/c++ program was compiled with from inside the program?
In my application as part of the logging information I would like to write which switches the program was compiled with, such as optimizations and pre-processor variable input by the compiler.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不是以任何标准方式。
通常是构建系统会在应用程序中内置的版本字符串中生成此类内容(但都不是自动的)。
Not in any standard way.
It is usually the build system that will generate such things in a version string that is built into the application (but none of it is automatic).
作为 Martin 答案的补充:作为此技术的一个示例,您可以查看 Vim 源代码 - grep for
all_cflags
或all_lflags
。As an addition to Martin's answer: as an example of this technique you can look at Vim sources - grep for
all_cflags
orall_lflags
.只有一些用于编译器开关的宏
http://gcc.gnu.org /onlinedocs/cpp/Common-Predefined-Macros.html
如果您确实需要完整的编译字符串,则应修改构建/制作脚本以将字符串作为常量或定义保存在特殊的
.h
文件中。There are only some macro for compiler switches
http://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html
If you do need a full compile string, you should modify your build/make script to save the string in the special
.h
file as constant or as define.另一种解决方案是简单地使用 shell 脚本包装 gcc 编译器调用,将标志保存到头文件中。然后,您可以将头文件包含在源文件中,例如:
调用该脚本
gcc_wrap -O0 main.c
将生成包含以下内容的头文件,然后继续编译 main.c 。An alternate solution is to simply wrap the gcc compiler invocation with a shell script that saves the flags to a header file. You can then include the header file in a source file, e.g.:
Invoking that script as
gcc_wrap -O0 main.c
will produce the header file with the following contents and then proceed with the compilation of main.c.在我的一个项目中,每个构建都会进入自己的目录,并且通常整个构建都有一个特定的名称,例如“parallel-debug”或“singlethread-O2”。通常,该目录中的日志文件从其位置隐式地向我们提供了所有信息。
无论如何,您可以做的是将 $(CC) 或 $(FLAGS) 或任何变量回显到文本文件中,然后让您的程序在启动时读取该文件。这不是元魔法,Scott Meyers 可能不会就有效的 C++ VII 采访您,但这个问题似乎并不值得那么头痛。
On one of my projects, every build went into its own directory, and usually the whole build had a specific name like "parallel-debug" or "singlethread-O2". Usually a log file in that directory gave us all the info implicitly from its location.
Anyway, what you can do is echo the $(CC) or $(FLAGS) or whatever variables into a text file, and then have your program read that file on startup. Its not meta magic and Scott Meyers might not interview you for effective C++ VII, but this problem doesn't seem to merit that much headache.