How to know (in GCC) when given macro/preprocessor symbol gets declared?

后端 未结 6 539
無奈伤痛
無奈伤痛 2020-12-10 05:17

Suppose I have #define foo in various header files. It may expand to some different things. I would like to know (when compiling a .cc file) when a #define is encountered, t

相关标签:
6条回答
  • 2020-12-10 05:44

    It wont help you find where it was defined but you can see the definition for a particular file by using the -E -dM flags

    g++ -E -dM file.cpp | grep MACRO
    
    0 讨论(0)
  • 2020-12-10 05:46

    Use -E :

    # shows preprocessed source with cpp internals removed
    g++ -E -P file.cc
    # shows preprocessed source kept with macros and include directives 
    g++ -E -dD -dI -P file.cc  
    

    The internals above are line-markers for gcc which are kinda confusing when you read the output. -P strips them

     -E  Stop after the preprocessing stage; do not run the compiler proper.  
         The output is in the form of preprocessed source code, which is sent to the 
         standard output.
    
         Input files which don't require preprocessing are ignored.

    Note: comments correctly complain this is only a partial solution. It won't tell you when a macro will be replaced. It shows you the preprocessed source, which can be helpful anyway.

    0 讨论(0)
  • 2020-12-10 05:54

    A Good IDE can do this for you on demand via some form of jump to definition.

    0 讨论(0)
  • 2020-12-10 05:56

    for the "to what it will expand" I use the -E switch in gcc which gives the preprocessed output. But there is no backtrace which macro came where from (or if there was a macro at all).

    Another option you might use is -g3, this adds debug information regarding the macros, i.e. you can later see in your debugger the definition of each macro.

    0 讨论(0)
  • 2020-12-10 06:03

    I would like to know (when compiling a .cc file) when a #define is encountered,

    I know a solution to that. Compile the file with the symbol already defined as illegal C++ code (the article linked to uses '@'). So, for GCC you would write

    gcc my_file.c -Dfoo=@
    

    When that expands it's guaranteed to cause a syntax error, and the compiler should tell you which file that syntax error is in, which will be very helpful.

    If you use the trick Raymond Chen suggests, the compiler may tell you where the "conflicting" definition came from, and may give you a list of how it got included. But there's no guarantee. Since I don't use macros (I prefer const and enum) I can't say if GCC is one of the smarter compilers in this regard. I don't believe the C or C++ standards say anything about this, other than once the preprocessor runs you lose all sorts of useful information.

    0 讨论(0)
  • 2020-12-10 06:04

    Use #warning. It's described here.

    0 讨论(0)
提交回复
热议问题