以下程序,当使用 GCC 4.8.1 编译为 C++ 时
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
int main() {
uintptr_t i = 0;
i--;
printf("%" PRIuPTR "\n", i);
return 0;
}
给出以下错误信息
a.cc: In function 'int main()':
a.cc:8:13: error: expected ')' before 'PRIuPTR'
printf("%" PRIuPTR "\n", i);
^
它可以使用 Microsoft 编译器正确编译和运行,甚至在编译为 C 时也可以使用 GCC。
我是不是遗漏了什么,或者这是 GCC 中的错误?如果是后者,是否有解决方法?
最佳答案
C 标准对包含 C++ 中的 C 头文件有如下说明:
C++ implementations should define these macros only when
__STDC_FORMAT_MACROS
is defined before<inttypes.h>
is included.
而且 GCC 似乎遵循了这个建议,而 Microsoft 没有。
与其定义此宏并包含已弃用的 C header ,更好的解决方案是使用 C++ header <cinttypes>
, 它无条件地定义了这些宏。 (如评论中所述,C++ 标准明确指出宏对 C++ header 没有影响。)
或者,当有更方便(和类型安全)的 C++ 替代方案时,停止使用 C 库,std::cout << i;
关于c++ - GCC 中的 PRIuPTR 预处理器错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26182336/