1

I'm starting a foray into using macros to generate data structures. Alas, I've run into a strange snag. I want to write the following macro:

#define CREATE_STRUCT(NAME) struct ##NAME { }

I attempt to use it like this:

CREATE_STRUCT(test);

However, it generates an error and the macro expansion apparently doesn't work. I've noticed that in every example of this type of macro expansion I've seen, there is an underscore (_) that precedes the ##<ARG> token. For example:

#define CREATE_STRUCT(NAME) struct _##NAME { }

This one works, but of course it throws an underscore at the beginning of the newly declared type.

So, there's a few questions here:

  1. Is there a way to avoid requiring a character to precede the ## token?
  2. What are the rules regarding the ## token in macros?

Thank you in advance!

Colin Basnett
  • 4,052
  • 2
  • 30
  • 49
  • I am not sure why you are using ## at all for your example. ## is used to join two symbols together. Try `#define CREATE_STRUCT(NAME) struct NAME { }` – Galik Jul 24 '14 at 03:31

1 Answers1

1

You don't need the token pasting operator unless you want to merge multiple tokens into one. For example get TestThis from Test and This. In your case you can just do:

 #define CREATE_STRUCT(NAME) struct NAME { }

If you run g++ -E file.cc on your macro, you will see that the preprocessor comes up with structtest { }; and this causes an error.

perreal
  • 94,503
  • 21
  • 155
  • 181