但是如果我想在 ASCII 上下文中使用 CONST_FILENAME 怎么办?如:
char *something = CONST_FILENAME;
L"okay.dat" 中的 L 不能与 " 用空格分隔。宽字符字符串是单个标记,您不能直接“将L 添加到它”。但是,您可以进行字符串连接:
#include <wchar.h>
#define A_STRING "xyz.txt"
/* MMT - Magical Mystery Tour */
#define MMT(x) L"" x
char a[] = A_STRING;
wchar_t w[] = MMT(A_STRING);
狡猾,但 GCC 可以接受。这很好,因为标准也是如此。这是来自 C99 标准:
§6.4.5 字符串文字
¶4 在翻译阶段 6,由任何序列指定的多字节字符序列
相邻字符和宽字符串文字标记连接成单个多字节
字符序列。如果任何标记是宽字符串文字标记,则结果
多字节字符序列被视为宽字符串文字;否则,它被视为
字符串文字。
测试代码:
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <wchar.h>
#define A_STRING "xyz.txt"
/* MMT - Magical Mystery Tour */
#define MMT(x) L"" x
static char a[] = A_STRING;
static wchar_t w[] = MMT(A_STRING);
int main(void)
{
int len1 = wcslen(w);
int len2 = sizeof(w) / sizeof(w[0]) - 1;
int len3 = strlen(a);
int len4 = sizeof(a) / sizeof(a[0]) - 1;
assert(len1 == len2);
assert(len3 == len4);
assert(len1 == len3);
printf("sizeof(a) = %zu; sizeof(w) = %zu\n", sizeof(a), sizeof(w));
for (int i = 0; i < len1; i++)
printf("%d = %d\n", i, (int)w[i]);
for (int i = 0; i < len1; i++)
printf("%d = %d\n", i, (int)a[i]);
return(0);
}
编译:
gcc -O3 -g -Wall -Wextra -std=c99 xx.c -o xx
示例输出:
sizeof(a) = 8; sizeof(w) = 32
0 = 120
1 = 121
2 = 122
3 = 46
4 = 116
5 = 120
6 = 116
0 = 120
1 = 121
2 = 122
3 = 46
4 = 116
5 = 120
6 = 116
测试平台
MacOS X 10.7.3 (Lion)。 64位编译。
i686-apple-darwin11-llvm-gcc-4.2 (GCC) 4.2.1(基于 Apple Inc. build 5658)(LLVM build 2335.15.00)