7

The approach to concatenate in C/C++ in a preprocessor macro is to use ##. The approach to stringify is to use #. I'm trying to concat AND stringify. This is generating a warning from g++ (3.3.2)

#define TOKENPASTE(x, y) x ## y
#define TOKENPASTE2(x, y) TOKENPASTE(x, y)      // concat
#define TOKENPASTE3(x, y) TOKENPASTE(#x, #y)    // concat-stringify (warnings)
const char* s = TOKENPASTE3(Hi, There)

It is not acceptable to get the warning

"test_utils/test_registration.h:34:38: warning: pasting ""Hi"" and ""There"" does not give a valid preprocessing token"

although (using the -E option) I see that it generates:

const char* s = "Hi""There";

Which looks right to me.

Any help will be appreciated.

5
  • 3
    Why are you using a version of GCC that's over a decade old? Commented Feb 11, 2015 at 14:00
  • 1
    It is actually a safety-critical fork from a decade ago. It is from WindRiver 653. That's out of my hands. Commented Feb 11, 2015 at 14:01
  • 1
    Well, you already have two strings, after #x and #y; you don't need to concat them into a single token, just use #x #y. Commented Feb 11, 2015 at 14:03
  • 2
    That concat is unnecessary. "Hi" "There" will be interpreted as "HiThere" even without doing so. Commented Feb 11, 2015 at 14:03
  • The preprocessor simply doesn't allow concatenation of strings using the concatenation operator. From this reference: "Only tokens that form a valid token together may be pasted". String-literal concatenation is handled by another compiler phase. Commented Feb 11, 2015 at 14:04

1 Answer 1

9

The preprocessor already concatenates adjacent string literals. So your macro is unnecessary. Example:

#define TOKENPASTE3(x, y) #x #y
const char* s = TOKENPASTE3(Hi, There);

becomes "Hi" "There". However, if you wanted to stick with your approach, you need to use an extra level of indirection to macro expand your new token:

#define STRINGIFY(x) #x
#define TOKENPASTE(x, y) STRINGIFY(x ## y)

becomes "HiThere".

Sign up to request clarification or add additional context in comments.

Comments

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.