Multi line preprocessor macros

noisy cat picture noisy cat · May 2, 2012 · Viewed 75.1k times · Source

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.

Answer

Ed S. picture Ed S. · May 2, 2012

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.