我在交叉编译时让cinttypes在mingw64-w64上正常工作时遇到了严重的麻烦。我已经将其简化为在docker中运行的最小示例。
inttypes_test.cpp
#include <cstdio>
#include <cstddef>
#include <cstdint>
#include <cinttypes>
#include <cstdarg>
__attribute__((format(printf, 1, 2))) static void myPrintf(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
vprintf(fmt, args);
va_end(args);
}
int main(int argc, const char** argv)
{
int i32 = 5;
int64_t i64 = 10;
uint64_t u64 = 20;
myPrintf("Testing int: %" PRId32 ", int64 = %" PRId64 ", size_t = %" PRIu64 "\n", i32, i64, u64);
return 0;
}
Dockerfile
FROM ubuntu:18.04
RUN apt-get update -y && \
apt-get install -y g++-mingw-w64-x86-64 && \
apt-get clean && \
rm -rf /var/lib/apt/lists/*
ADD inttypes_test.cpp /inttypes-test/
RUN cd "/inttypes-test" && \
/usr/bin/x86_64-w64-mingw32-g++ -Wall -Werror -c inttypes_test.cpp
运行的结果为:
inttypes_test.cpp: In function 'int main(int, const char**)':
inttypes_test.cpp:20:100: error: unknown conversion type character 'l' in format [-Werror=format=]
myPrintf("Testing int: %" PRId32 ", int64 = %" PRId64 ", size_t = %" PRIu64 "\n", i32, i64, u64);
^
inttypes_test.cpp:20:100: error: unknown conversion type character 'l' in format [-Werror=format=]
inttypes_test.cpp:20:100: error: too many arguments for format [-Werror=format-extra-args]
因此,我有点以为
<cinttypes>
header 的全部要针对这些平台特定的差异。难道我做错了什么? 最佳答案
inttypes
是一个红色鲱鱼,您从myPrintf("%lld", 1LL);
收到相同的警告。它警告您使用ll
,该程序在您的程序中由inttypes宏(正确)提供。
这是MinGW较旧版本的遗留之处,在该版本中,printf格式通过MSVCRT重定向,该格式未处理%lld
,因此发出警告是适当的。
您可以通过在文件中添加新的顶行来解决该问题(在包括任何标准之前):
#define __USE_MINGW_ANSI_STDIO 1
然后使用以下属性:
__attribute__((format(__MINGW_PRINTF_FORMAT, 1, 2)))
static void myPrintf(const char* fmt, ...)
这指示mingw-w64使用其自己的符合ISO标准的printf实现,并相应地使
-Wformat
警告匹配。 Link to documentation在我的系统(g++ 8.2.1)上,即使没有第一行,实际上也可以正确使用
%lld
等,因此我怀疑他们可能已将其修复为默认情况下使用ISO stdio而不是MS stdio。也许MS stdio现在知道%lld
了。值得指出一个错误报告,指出
__attribute__((format(printf
应该根据所使用的stdio自动正确工作,而无需执行此替代方法。