9

Can a multi-line raw string literal be an argument of a preprocessor macro?

#define IDENTITY(x) x

int main()
{
    IDENTITY(R"(
    )");
}

This code doesn't compile in both g++4.7.2 and VC++11 (Nov.CTP).
Is it a compiler (lexer) bug?

3
  • 1
    It seems to be either a lexer or a pre-processor problem, in GCC at least. If I add a pre-processor line-continuation (ending the line in a backslash) it compiles, but the string contain the line-continuation character. Tested with GCC 4.7.2. Commented Nov 30, 2012 at 17:25
  • 1
    I've opened a bug to track the issue in the Visual C++ CTP. Commented Nov 30, 2012 at 20:47
  • 1
    For what it's worth, Clang 3.1 has no problem compiling your example. Commented Jan 17, 2013 at 17:26

1 Answer 1

2

Multiple line macro invocations are legal - since you are using a raw string literal it should have compiled

There is a known GCC bug for this:

http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52852

If you had been using regular (nonraw) strings it would have been illegal.

This should have compiled:

printf(R"HELLO
    WORLD\n");

But not this:

printf("HELLO
    WORLD\n");

This should be coded as

printf("HELLO\nWORLD\n"); 

if a new line is intended between HELLO and WORLD or as

printf("HELLO "
    "WORLD\n");

If no intervening new line was intended.

Do you want a new line in your literal? If so then couldn't you use

  IDENTITY("(\n)");

The C compiler documentation at

http://gcc.gnu.org/onlinedocs/cpp.pdf

States that in section 3.3 (Macro Arguments) that

"The invocation of the macro need not be 
restricted to a single logical line—it can cross 
as many lines in the source file as you wish."
Sign up to request clarification or add additional context in comments.

2 Comments

Your first example doesn't compile because it's an ordinary string literal. The OP used a raw string literal, which can contain source-file newlines (see [lex.string], esp. para 4 & 5). I side with the OP that it's a compiler bug.
How can you do this in just C, not C++? error: use of undeclared identifier 'R'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.