how to define macro to convert concatenated char string to wchar_t string in C

3k views Asked by At

Like _T() macro in Visual Studio, I defined and used my own _L macro as:

#define _L(x)  __L(x)
#define __L(x) L ## x

It works for:

wprintf(_L("abc\n"));

But gets a compilation error for:

wprintf(_L("abc\n""def\n"));

It reports “string literals with Iifferent character kinds cannot be concatenated”.
I also did:

#define _L2(x)  __L2(x)
#define __L2(x) L ## #x
wprintf(_L2("abc\n""def\n"));

The code gets compiled, but the \n doesn't work as an escape sequence of a new line. The \n becomes two characters, and the output of wprintf is:

"abc\n""def\n"

How I can have a macro to convert two concatenated char string to wchar_t? The problem is I have some already existing macros:

#define BAR  "The fist line\n" \
             "The second line\n"

I want to covert them to a wchar string during compilation. The compiler is ICC in windows.

Edit:
The _L macro works in gcc, the MSVC and ICC didn't works, it's a compiler bug. Thanks @R.. to comment me.

1

There are 1 answers

3
ugoren On

I don't think you can do this.

Macros just do simple text processing. They can add L in the beginning, but can't tell that "abc\n" "def\n" are two strings, which need adding L twice.

You can make progress if you pass the strings to the macro separated by commas, rather than concatenated:
L("abc\n", "def\n")

It's trivial to define L that accepts exactly two strings:
#define L2(a,b) _L(a) _L(b)
Generalizing it to have a single macro that gets any number of parameters and adds Ls in the correct place is possible, but more complicated. You can find clever macros doing such things in Jens Gustedt's P99 macros.