tags:

views:

1664

answers:

6

How do I write a cpp macro which expands to include newlines?

A: 

use \, like so:

#define my_multiline_macro(a, b, c) \
if(a) { \
  b += c; \
}
Branan
This expands to "if(a) { b += c }", with no newlines. Try it with gcc -E.
Steve Jessop
It does. But it lets you edit the newline in a multi-line fashion, shich is what I think the OP wanted
Branan
+9  A: 

C & C++ compilers ignore unquoted whitespace (except for the > > template issue), so getting a macro to emit newlines doesn't really make sense. You can make a macro span several lines by ending each line of the macro with a backslash, but this doesn't output newlines.

Mike Thompson
A: 

Not quite sure what you're asking here. Do you want a macro on multiple lines?

#define NEWLINE_MACRO(x) line1 \
line2 \
line3

Additionally, if you would like to include a literal in your macro:

#define NEWLINE_MACRO(x) ##x

what you you put in x will be put in place of ##x, so:

NEWLINE_MACRO( line1 ) // is replaced with line1

This can be helpful for making custom global functions then just need part of the function name changed.

Also:

#define NEWLINE_MACRO(x) #x // stringify x

Will put quotes around x

PiNoYBoY82
+4  A: 

The c compiler is aware of white space, but doesn't distinguish between spaces, tabs or new lines.

If you mean how do I have a new line inside a string in a macro, then:

#define SOME_STRING "Some string\n with a new line."

will work.

David L Morris
A: 

Use the \ at the end of the line. I've seen a lot of C macos where they use a do...while(0)

#define foo() do \
{
  //code goes here \
  \
  \
}while(0);

Also, remember to use parenthases in many instances.

Example:

#define foo(x) a+b
//should be
#define foo(x) (a+b)
Charles Graham
The macro definition should not include the trailing semicolon. This makes the macro call look and act like more like a function call.
Trent
+1  A: 

It is not possible. It would only be relevant if you were looking at listing files or pre-processor output.

A common technique in writing macros so that they are easier to read is to use the \ character to continue the macro onto a following line.

I (believe I) have seen compilers that include new lines in the expanded macros in listing output - for your benefit. This is only of use to us poor humans reading the expanded macros to try to understand what we really asked the compiler to do. it makes no difference to the compiler.

The C & C++ languages treat all whitespace outside of strings in the same way. Just as a separator.

itj