Multiple Line Preprocessor Macros

How to make a multi-line macro preprocessor? 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 make this work?

This is just an example; a real macro can be very long.

+43
c ++ c c-preprocessor
May 2 '12 at 18:25
source share
4 answers

You use \ as an escape character to continue the line.

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

EDIT: As the @abelenky comment noted in the comments, the \ character must be the last character in the string . If this is not the case (even if it is just a space after that), you will get confused error messages on each line after it.

+78
May 02 '12 at 18:27
source share

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

 #define F(x) (x) \ * \ (x) 
+10
May 2 '12 at 18:29
source share

PLEASE NOTE , as stated in the statement of Kerrek S.B. and coaddit, which should be indicated in the accepted answer, ALWAYS place curly brackets around your arguments. The sqr example is a 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 place the curly braces around it correctly, #define sqr(x) ((x)*(x))
you get ((1 + 5) * (1 + 5)) or what we need 36 ... beautiful.

Ed S. will have the same problem with "swap"

+9
May 02 '12 at 19:20
source share

You need to exit the new line at the end of the line, escaping it with \ :

 #define sqr(X) \ ((X)*(X)) 
+2
May 02 '12 at 18:30
source share



All Articles