How to make G++ preprocessor output a newline in a macro?

前端 未结 8 843
隐瞒了意图╮
隐瞒了意图╮ 2020-12-01 15:55

Is there a way in gcc/g++ 4.* to write a macro that expands into several lines?

The following code:

#define A X \\ Y

Expands into

相关标签:
8条回答
  • 2020-12-01 16:05

    Make the macro generate a special markup, say __CR__, then pipe the result of CPP into a script which translates the macro to a true newline, for example, sed 's/__CR__/\n/g'.

    I just found this useful to generate a code pattern to be filled by hand. It is quite easier when the code is readable.

    0 讨论(0)
  • 2020-12-01 16:10

    Is this what you want:

    #define A "X \nY"
    
    0 讨论(0)
  • 2020-12-01 16:22

    Got it!

    #define anlb /*
    */ A /*
    */ B
    
    anlb anlb
    

    gcc -E -CC nl.c
    

    /*
    */ A /*
    */ B /*
    */ A /*
    */ B
    
    0 讨论(0)
  • 2020-12-01 16:22

    I'm pretty sure CPP, being designed for C which doesn't care for newlines, and all, can't handle this kind of work. Still you can mark wanted newlines with some special marker string and pass the result through sed or awk to get what you want.

    0 讨论(0)
  • 2020-12-01 16:23

    You can just put a magic character sequence in the macro, e.g.

    #define X(y,z) y nl z
    

    run gcc -E infile | sed g/s/nl/\n/ > whatever

    (Maybe not exactly right, but you get the idea, right? Pipe it through sed or tr or run Emacs on the output.)

    I do this sometimes to use C macros to generate source code and no I don't want to learn how to do it in Perl or M4 or yet another tool.

    0 讨论(0)
  • 2020-12-01 16:25

    From the docs:

    in the present implementation, the entire expansion comes out on one line

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