G ++: Is there a way to access compilation flags inside compiled code?

Is there a way (for example, certain constants) for accessing the compilation flags with which the compiler was launched inside the compiled code.

For example, I need a program that records the flags with which it was compiled.

int main(){ std::cout << COMPILE_FLAGS << std::endl; } 

Are there such constants for gcc / g ++? Or even better: Are there constants that are defined in both gcc and clang?

I am particularly interested in exploring the level of optimization and the meaning of the -march flag. So, if there are no constants displaying all flags, are there at least those that display these values?

+6
source share
2 answers

The following command displays all the predefined macros:

 g++ -dM -E - < /dev/null 

This works with both gcc and g ++. You can test yourself - unfortunately, there is no macro, which gives easy access to the full gcc / g ++ command line.

Fortunately, most of the -m ... flags lead to the creation of suitable precompiler macros. For example, -m64 defines __ x86_64 and -m32 defines ___ code_model_32 __ . Or for -march : -march = core-avx2 leads to #define __core_avx2__ 1 .

Just add the parameter you need to check in the command line above and check the result for the new macro.

+1
source

If you can change the flag compilation or script that generates the compilation command, you can add -DCOMPILE_FLAGS = <flags that interest you> to your assembly to actually create this constant.

From the GCC manual:

-D name = definition The contents of the definition are symbolized and processed as if they appeared during the third phase of translation in '#define. In particular, the definition will be truncated by inline newline characters.

0
source

Source: https://habr.com/ru/post/979514/


All Articles