Run a “light” preprocessor for GCC

前端 未结 5 810
误落风尘
误落风尘 2021-02-07 10:37

Is there a way to run the GCC preprocessor, but only for user-defined macros?

I have a few one-liners and some #ifdef, etc. conditionals, and I want to see

相关标签:
5条回答
  • 2021-02-07 11:21

    If you just want macro expansions and skip the #include handling, you can try this repo. It is a fork of the original pcpp. I added a --no-include option to skip the handling of #include directive. All other macros will be processed based on your marco input to pcpp.

    0 讨论(0)
  • 2021-02-07 11:23

    Call cpp directly, e.g.

    $ cat >foo.c <<EOF
    #define FOO
    #ifdef FOO
    foo is defined
    #else
    foo is not defined
    #endif
    EOF
    
    $ cpp foo.c
    # 1 "foo.c"
    # 1 "<built-in>"
    # 1 "<command-line>"
    # 1 "foo.c"
    
    
    foo is defined
    

    Of course, if you include any headers then those will be included in the output. One way to avoid that might be to just grep -v out the lines with #includes (or perhaps just ones with #include < and allow #include "). Or you could specify the -nostdinc option to remove just standard includes (but possibly leave in local libraries unless you specify include paths so that they won't be found) - this would warn about missing headers, though.

    Edit: Or use the preprocessor itself to make the inclusion of headers conditional, wrap them in something like #ifndef TESTING_PREPROCESSOR and use -DTESTING_PREPROCESSOR.

    0 讨论(0)
  • 2021-02-07 11:27
    gcc  -E inputfile.c > outputfile.c
    

    outputfile.c will have your preprocessed code, but all macros will be expanded.

    I find this trick very useful when debugging compilation of large systems with tons of includes, compiler flags, and makefile variables. It will expose include files that don't have header guards, and a bunch of other problems too.

    0 讨论(0)
  • 2021-02-07 11:42
    cpp -nostdinc program.c
    
    0 讨论(0)
  • 2021-02-07 11:42

    One may use tools like unifdef, unifdefall — remove preprocessor conditionals from code

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