简体   繁体   中英

Access GCC Compiler Switches From Inside C/C++ Program

It is possible to access the gcc compiler switches ac/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.

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_cflagsall_lflags

There are only some macro for compiler switches

http://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html

__OPTIMIZE__
 __OPTIMIZE_SIZE__
 __NO_INLINE__

__OPTIMIZE__ is defined in all optimizing compilations. __OPTIMIZE_SIZE__ is defined if the compiler is optimizing for size, not speed. __NO_INLINE__ is defined if no functions will be inlined into their callers (when not optimizing, or when inlining has been specifically disabled by -fno-inline).

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.

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, eg:

#!/bin/sh

echo "#define GCC_OPTIONS \"$*\"" > gcc_options.h
exec gcc $@

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.

#define GCC_OPTIONS "-O0 main.c"

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM