交叉编译Azure IoT C SDK时SIZE_MAX重定义问题咨询
交叉编译Azure IoT C SDK时SIZE_MAX重定义问题解析
问题现象
本地编译Azure IoT C SDK正常,但交叉编译时触发如下错误:
[ 33%] Building C object out/uamqp/CMakeFiles/uamqp.dir/src/header_detect_io.c.o In file included from /home/abertulli/two_lidars/azure-iot-sdk-c/uamqp/inc/azure_uamqp_c/server_protocol_io.h:11:0, from /home/abertulli/two_lidars/azure-iot-sdk-c/uamqp/src/header_detect_io.c:13: /opt/box-root-fs/usr/include/stdint.h:266:0: error: "SIZE_MAX" redefined [-Werror] # define SIZE_MAX (4294967295U) In file included from /home/abertulli/two_lidars/azure-iot-sdk-c/uamqp/src/header_detect_io.c:11:0: /home/abertulli/two_lidars/azure-iot-sdk-c/c-utility/inc/azure_c_shared_utility/safe_math.h:8:0: note: this is the location of the previous definition #define SIZE_MAX ((size_t)((size_t)~(size_t)0)) cc1: all warnings being treated as errors make[2]: *** [out/uamqp/CMakeFiles/uamqp.dir/build.make:202: out/uamqp/CMakeFiles/uamqp.dir/src/header_detect_io.c.o] Error 1 make[1]: *** [CMakeFiles/Makefile2:594: out/uamqp/CMakeFiles/uamqp.dir/all] Error 2 make: *** [Makefile:136: all] Error 2
相关代码片段
交叉编译sysroot中的stdint.h
/* Limit of `size_t' type. */ # if __WORDSIZE == 64 # define SIZE_MAX (18446744073709551615UL) # else # ifdef __WORDSIZE32_SIZE_ULONG # define SIZE_MAX (4294967295UL) # else # define SIZE_MAX (4294967295U) // <-------- 冲突位置 # endif # endif
Azure IoT C SDK中的safe_math.h
#ifndef SIZE_MAX #define SIZE_MAX ((size_t)((size_t)~(size_t)0)) // <-------- 冲突位置 #endif
疑问解答
1. 为何已用#ifndef SIZE_MAX保护仍出现重定义?
问题出在头文件包含顺序:
在header_detect_io.c中,先包含了SDK的safe_math.h——此时SIZE_MAX未被定义,所以SDK的宏被写入;之后通过server_protocol_io.h引入了交叉编译工具链的stdint.h,而这个stdint.h里的SIZE_MAX定义没有加#ifndef保护,直接重复定义,触发编译错误。
2. 为何仅交叉编译时触发该问题?
本地编译使用的系统标准stdint.h(比如GNU libc的头文件)中,SIZE_MAX的定义带有#ifndef SIZE_MAX的保护逻辑,会先检查是否已定义,避免重复;但你使用的交叉编译sysroot中的stdint.h缺少这个保护,因此只有交叉编译时会触发冲突。
3. 是否需要修改sysroot中的头文件?
不推荐直接修改sysroot的系统头文件,避免破坏工具链的兼容性和完整性。推荐以下修复方案:
- 调整头文件包含顺序:在所有引用
safe_math.h的源文件中,先包含系统的stdint.h,再包含safe_math.h,这样safe_math.h中的#ifndef SIZE_MAX会检测到已定义,不会重复写入宏。 - 修改SDK的
safe_math.h:优化宏定义逻辑,比如增加对标准库定义的判断,例如:#if !defined(SIZE_MAX) && !defined(__STDC_VERSION__) #define SIZE_MAX ((size_t)((size_t)~(size_t)0)) #endif - 临时规避方案:编译时添加编译选项
-Wno-error=redefinition,将该重定义警告转为非错误,但此方案仅适合临时测试,不建议长期使用,可能掩盖其他潜在问题。
内容的提问来源于stack exchange,提问作者Alessandro Bertulli
相关产品推荐
相关产品推荐

