使用 sys/socket.h 宏时的神秘类型转换警告
Mysterious type conversion warning when using sys/socket.h macro
我正在尝试使用 GCC 9.1 (iso9899:1999) 和 GNU make 4.2 解决我们基于 Solaris 11 64 位的 C 代码库中的转换警告,我遇到了这个:
warning: unsigned conversion from ‘int’ to ‘long unsigned int’ changes value from ‘-8’ to ‘18446744073709551608’ [-Wsign-conversion]
187 | char ccmsg[CMSG_SPACE(sizeof(int))];
| ^~~~~~~~~~
我知道 CMSG_SPACE
在 sys/socket.h
中定义为:
/* Amount of space + padding needed for a message of length l */
#define CMSG_SPACE(l) \
((unsigned int)_CMSG_HDR_ALIGN(sizeof (struct cmsghdr) + (l)))
但是,我不了解转换发生在何处以及如何解决它。 Google 没有帮助。
编辑
根据评论中的要求,这里是头文件中的更多信息:
#if defined(__sparc)
/* To maintain backward compatibility, alignment needs to be 8 on sparc. */
#define _CMSG_HDR_ALIGNMENT 8
#else
/* for __amd64 (and other future architectures) */
#define _CMSG_HDR_ALIGNMENT 4
#endif /* defined(__sparc) */
#define _CMSG_DATA_ALIGNMENT (sizeof (int))
#define _CMSG_HDR_ALIGN(x) (((uintptr_t)(x) + _CMSG_HDR_ALIGNMENT - 1) & \
~(_CMSG_HDR_ALIGNMENT - 1))
#define _CMSG_DATA_ALIGN(x) (((uintptr_t)(x) + _CMSG_DATA_ALIGNMENT - 1) & \
~(_CMSG_DATA_ALIGNMENT - 1))
#define CMSG_DATA(c) \
((unsigned char *)_CMSG_DATA_ALIGN((struct cmsghdr *)(c) + 1))
-8
来自 ~(_CMSG_HDR_ALIGNMENT - 1)
,long unsigned int
转换来自 uintptr_t
。
编译器警告在应用 &
运算符之前将 -8
转换为 uintptr_t
。
NOTE: answer is from a comment left by @jxh
我正在尝试使用 GCC 9.1 (iso9899:1999) 和 GNU make 4.2 解决我们基于 Solaris 11 64 位的 C 代码库中的转换警告,我遇到了这个:
warning: unsigned conversion from ‘int’ to ‘long unsigned int’ changes value from ‘-8’ to ‘18446744073709551608’ [-Wsign-conversion]
187 | char ccmsg[CMSG_SPACE(sizeof(int))];
| ^~~~~~~~~~
我知道 CMSG_SPACE
在 sys/socket.h
中定义为:
/* Amount of space + padding needed for a message of length l */
#define CMSG_SPACE(l) \
((unsigned int)_CMSG_HDR_ALIGN(sizeof (struct cmsghdr) + (l)))
但是,我不了解转换发生在何处以及如何解决它。 Google 没有帮助。
编辑 根据评论中的要求,这里是头文件中的更多信息:
#if defined(__sparc)
/* To maintain backward compatibility, alignment needs to be 8 on sparc. */
#define _CMSG_HDR_ALIGNMENT 8
#else
/* for __amd64 (and other future architectures) */
#define _CMSG_HDR_ALIGNMENT 4
#endif /* defined(__sparc) */
#define _CMSG_DATA_ALIGNMENT (sizeof (int))
#define _CMSG_HDR_ALIGN(x) (((uintptr_t)(x) + _CMSG_HDR_ALIGNMENT - 1) & \
~(_CMSG_HDR_ALIGNMENT - 1))
#define _CMSG_DATA_ALIGN(x) (((uintptr_t)(x) + _CMSG_DATA_ALIGNMENT - 1) & \
~(_CMSG_DATA_ALIGNMENT - 1))
#define CMSG_DATA(c) \
((unsigned char *)_CMSG_DATA_ALIGN((struct cmsghdr *)(c) + 1))
-8
来自 ~(_CMSG_HDR_ALIGNMENT - 1)
,long unsigned int
转换来自 uintptr_t
。
编译器警告在应用 &
运算符之前将 -8
转换为 uintptr_t
。
NOTE: answer is from a comment left by @jxh