How to define a macro to convert a concatenated char string to a wchar_t string in C

Like the _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 it gets a compilation error for:

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

He reports that string literals with different types of characters cannot be combined. "
I also did:

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

The code compiles, but \n does not work as an escape sequence for a new line. \n becomes two characters, and the output is wprintf :

"a \ p" "Protection \ p"

How can I create a macro to convert two concatenated char strings to wchar_t ? The problem is that I have existing macros:

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

I want to hide them until the wchar line at compile time. The compiler is the ICC in windows.

Edit :
The _L macro works in gcc, MSVC and ICC do not work, this is a compiler error. Thanks @R .. comment me.

+6
source share
1 answer

I do not think you can do this.

Macros just do simple word processing. They can add L at the beginning, but they cannot say that "abc\n" "def\n" are two lines for which you need to add L twice.

You can make progress by passing strings to a macro, separated by commas, rather than concatenated:
L("abc\n", "def\n")

It is trivial to define L that takes exactly two lines:
#define L2(a,b) _L(a) _L(b)
Generalizing it to have one macro that gets any number of parameters, and adds L to the right place, but more complicated. You can find smart macros that do such things in Jens Gustedt P99 macros .

+2
source

Source: https://habr.com/ru/post/916524/


All Articles