简体   繁体   English

C预处理器文字构造

[英]C preprocessor Literal Construction

My problem is as follows: 我的问题如下:

I have a string literal that is macro-ed like so 我有一个像这样的宏编辑的字符串文字

#define TITLE "Title"

But there are instances when I need to pass in a wide char variant of this string. 但有些情况下,我需要传入此字符串的宽字符变体。 I want to be able to pass L"Title" to those functions. 我希望能够将L"Title"传递给这些函数。 So naturally, I set out trying to define a new macro W_TITLE in terms of TITLE . 很自然地,我开始尝试根据TITLE定义一个新的宏W_TITLE

But I have no luck, all my approaches (listed bellow) have failed. 但是我没有运气,我所有的方法(列在下面)都失败了。 Please tell me how such magic can be accomplished. 请告诉我如何完成这样的魔术。

I tried 我试过了

#define W_TITLE L##TITLE
#define W_TITLE #L TITLE
#define W_TITLE ##L TITLE

But they all fail... 但他们都失败了......

Try this: 尝试这个:

#define WIDEN_(exp)   L##exp
#define WIDEN(exp)    WIDEN_(exp)
#define TITLE         "Title"
#define W_TITLE       WIDEN(TITLE)

You need to force an expansion through an intermediate macro to get what you're looking for. 您需要通过中间宏强制扩展以获得您正在寻找的内容。

#include <stdio.h>

#define WIDEN_(exp)   L##exp
#define WIDEN(exp)    WIDEN_(exp)
#define TITLE         "Title"
#define W_TITLE       WIDEN(TITLE)

int main(int argc, char *argv[])
{
    printf("%s\n", TITLE);
    wprintf(L"%ls\n", W_TITLE);
    return 0;
}

Result: 结果:

Title
Title

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM