[ACCEPTED]-How to make G++ preprocessor output a newline in a macro?-c-preprocessor

Accepted answer
Score: 32

Got it!

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

anlb anlb

Down arrow

gcc -E -CC nl.c

Down arrow

/*
*/ A /*
*/ B /*
*/ A /*
*/ B

0

Score: 9

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

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

Score: 6

You can just put a magic character sequence 6 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 5 right, but you get the idea, right? Pipe 4 it through sed or tr or run Emacs on the output.)

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

Score: 3

Putting a side the fact that not being able 12 to put newlines in macros create unreadable 11 code, making it harder to debug preprocessor 10 outputs. It is true that C and C++ might 9 not care about newlines, but the C preprocessor 8 does.

I would really like to make a macro 7 ConditionalDefine(x,y) that outputs the 6 following.

    #ifdef x
    #define y
    #endif

The following defines do something 5 close:

    #define hash #
    #define nl
    #define _def_p8(A,B) A ifdef _P8_K60_BOARD_ A define B  A endif
    #define X_def_p8(A,B) _def_p8(A,B)
    #define def_p8(A) X_def_p8(nl hash,A)

expanding the following:

    def_p8(PTPD_DBGA 0)

results in:

    # ifdef _P8_K60_BOARD_ # define PTPD_DBGA 0    # endif

But 4 without being able to put new lines in before 3 the hashes it would not work as intended. It 2 is also annoying the hoops you have to jump 1 through just to get that close.

Score: 2

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

Score: 2

From the docs:

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

Score: 1

Why does the spacing matter?

The imake program 11 used in (older?) builds of X11 used the 10 C pre-processor to generate makefiles, but 9 imake program used a special technique of 8 indicating line endings with @@ symbols 7 at the ends of lines, and then post-processed 6 the output of the pre-processor to replace 5 the @@ symbols with newlines.

From this design, I 4 conclude that there is no reliable way to 3 obtain newlines from expanded macros in 2 C (or C++). Indeed, for C, there is no 1 need since:

  • C does not care about newlines compared with white space after the C pre-processor is run, and
  • You cannot generate pre-processor directives from macros etc.

More Related questions