Access GCC Compiler Switches From Inside C/C++ Program
It is possible to access the gcc compiler switches a c/c++ program was compiled with from inside the progra开发者_开发问答m?
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).
As an addition to Martin's answer: as an example of this technique you can look at Vim sources - grep for all_cflags
or all_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, e.g.:
#!/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.
精彩评论