Multi line preprocessor macros

2019-01-06 14:57发布

问题:

How to make multi line preprocessor macro? I know how to make one line:

#define sqr(X) (X*X)

but I need something like this:

#define someMacro(X)
    class X : public otherClass
    {
         int foo;
         void doFoo();
    };

How can I get this to work?

This is only an example, the real macro may be very long.

回答1:

You use \ as a line continuation escape character.

#define swap(a, b) {               \
                       (a) ^= (b); \
                       (b) ^= (a); \
                       (a) ^= (b); \
                   }

EDIT: As @abelenky pointed out in the comments, the \ character must be the last character on the line. If it is not (even if it is just white space afterward) you will get confusing error messages on each line after it.



回答2:

You can make a macro span multiple lines by putting a backslash (\) at the end of each line:

#define F(x) (x)   \
              *    \
             (x)


回答3:

PLEASE NOTE as Kerrek SB and coaddict pointed out, which should have been pointed out in the accepted answer, ALWAYS place braces around your arguments. The sqr example is the simple example taught in CompSci courses.

Here's the problem: If you define it the way you did what happens when you say "sqr(1+5)"? You get "1+5*1+5" or 11
If you correctly place braces around it, #define sqr(x) ((x)*(x))
you get ((1+5) * (1+5)) or what we wanted 36 ...beautiful.

Ed S. is going to have the same problem with 'swap'



回答4:

You need to escape the newline at the end of the line by escaping it with a \:

#define sqr(X) \
        ((X)*(X))