42

Possible Duplicate:
C Macros to create strings

I have a function which accepts one argument of type char*, like f("string");
If the string argument is defined by-the-fly in the function call, how can macros be expanded within the string body?

For example:

#define COLOR #00ff00
f("abc COLOR");

would be equivalent to

f("abc #00ff00");

but instead the expansion is not performed, and the function receives literally abc COLOR.

In particular, I need to expand the macro to exactly \"#00ff00\", so that this quoted token is concatenated with the rest of the string argument passed to f(), quotes included; that is, the preprocessor has to finish his job and welcome the compiler transforming the code from f("abc COLOR"); to f("abc \"#00ff00\"");

Community
  • 1
  • 1
davide
  • 2,082
  • 3
  • 21
  • 30

2 Answers2

54

You can't expand macros in strings, but you can write

#define COLOR "#00ff00"

f("abc "COLOR);

Remember that this concatenation is done by the C preprocessor, and is only a feature to concatenate plain strings, not variables or so.

András Kovács
  • 29,931
  • 3
  • 53
  • 99
tomahh
  • 13,441
  • 3
  • 49
  • 70
  • Is this equivalent to passing 2 arguments to f() ? – davide Oct 18 '12 at 16:11
  • 6
    @davide no, putting two string literals next to each other makes the C compiler concatenate them. – singpolyma Oct 18 '12 at 16:12
  • 3
    No, the strings will be concat by the compiler. At compile time, the string will result in "abc #00ff00" – tomahh Oct 18 '12 at 16:13
  • 9
    I believe the concatenation `"abc ""#00ff00"` to `"abc #00ff00"`is performed by compiler instead of preprocessor. https://gcc.gnu.org/onlinedocs/cpp/Stringification.html Notice in the second paragraph: `The preprocessor will replace the stringified arguments with string constants. The C compiler will then combine all the adjacent string constants into one long string.` – Barun Aug 14 '14 at 07:01
4
#define COLOR "#00ff00"
f("abc "COLOR);
singpolyma
  • 10,999
  • 5
  • 47
  • 71
  • 8
    I think it's worth noting that this works because C "automatically concatenates" two strings if they appear without anything in between. – phimuemue Oct 18 '12 at 16:23