如何在 Visual Studio 2013 中将 stdint 类型与 _tprintf 一起使用?

2023-12-27

举个例子:

char* fileName = "C:\\windows\\system32\\kernel32.dll";
uint32_t fileSize = 1163264;
printf("The size of %s is %"PRIu32"\n", fileName, fileSize);

一切都很好,现在如果我们想要透明的 unicode 支持tchar.h代码如下所示:

TCHAR* fileName = _T("C:\\windows\\system32\\kernel32.dll");
uint32_t fileSize = 1163264;
_tprintf(_T("The size of %s is %")_T(PRIu32)_T("\n"), fileName, fileSize);

如果 unicode 是这样的话,这有效not定义的。但是,如果定义了 unicode,编译器将中止并出现以下错误:

error C2308: concatenating mismatched strings
Concatenating wide "The size of %s is %l" with narrow "u"

现在看看微软的 inttypes.h 我看到:

...
#define _PFX_32  "l"
...
#define PRIu32       _PFX_32 "u"

这意味着_T(PRIu32)在上面的例子中解析为:

_T("l" "u")

...这当然不能工作并解释了正确的编译器错误。

因此我的问题是微软如何想象我们将他们的 inttypes.h 定义与 _tprintf 一起使用?


According1 to the current C standard, only one of the character sequences (read as: a string) must be prefixed by a an encoding prefix, and the rest of them are treated to have the same prefix, and are concatenated into a single string.

编码前缀由_T宏决定。如果未定义 UNICODE,它将解析为空,否则它将在前面添加L到论点。

解决方案是在第一个字符串上使用 _T 宏,其余字符串上不使用宏,并且它们将使用相同的编码:

_tprintf(_T("The size of %s is %") PRIu32 "\n", fileName, fileSize);

但您使用的 Visual Studio 版本不兼容 C99,因此缺少此功能。这似乎已在 Visual Studio 2015 中修复。

The same usage is demonstrated in the example2 in the standard.


1 (Quoted from: ISO/IEC 9899:201x 6.4.5 String literals 5)
In translation phase 6, the multibyte character sequences specified by any sequence of adjacent character and identically-prefixed string literal tokens are concatenated into a single multibyte character sequence. If any of the tokens has an encoding prefix, the resulting multibyte character sequence is treated as having the same prefix; otherwise, it is treated as a character string literal. Whether differently-prefixed wide string literal tokens can be concatenated and, if so, the treatment of the resulting multibyte character sequence are implementation-defined.

2 (Quoted from: ISO/IEC 9899:201x 7.8.1 Macros for format specifiers 7)
wprintf(L"The largest integer value is %020" PRIxMAX "\n", i);

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Visual Studio 2013 中将 stdint 类型与 _tprintf 一起使用? 的相关文章

随机推荐