Linux/POSIX ABI是否定义int类型大小?涉及ABI兼容性疑问
int大小与POSIX兼容性的问题 Great question—this touches on a key intersection of C standard flexibility, POSIX requirements, and system ABI guarantees, which is super important for cross-compiler and cross-process compatibility.
Let’s break this down step by step:
1. C标准的模糊性
First, the C standard (C99, C11, etc.) does not define a fixed size for int—it only mandates that:
sizeof(int) >= sizeof(short)intmust be able to hold values from at least-32767to32767(so a minimum of 16 bits).
This leaves room for compiler/platform variation in theory, but practice on UNIX/Linux systems is much stricter.
2. POSIX与系统ABI的强制约定
While POSIX doesn’t explicitly spell out the size of int, it imposes indirect constraints that, combined with system ABI (Application Binary Interface) rules, lock in int to 4 bytes (32 bits) on both 32-bit and 64-bit UNIX/Linux systems:
- File descriptor usage: POSIX specifies that file descriptors are represented as
intvalues. For inter-process communication (like passing fds via UNIX sockets’cmsghdrstructure), the size ofintmust be consistent across all processes and compiled code—otherwise, the data layout in control messages would break, leading to corrupted file descriptors or crashes. - System ABI compliance: All major UNIX/Linux systems (including Linux, BSD, Solaris) define their ABIs (e.g., System V ABI for x86-64, i386 System V ABI) to set
intas 4 bytes, regardless of the system’s word size. Compilers targeting these systems must adhere to the ABI—so GCC, Clang, and other compilers will all use 4-byteintfor these platforms, eliminating ABI incompatibility between them.
3. Practical confirmation
As you found, this is a consistent practice across UNIX/Linux platforms: both 32-bit and 64-bit systems use 4-byte int. This isn’t just a convention—it’s a hard requirement for system-level compatibility, so you won’t encounter compilers deviating from this on these systems.
In short: While the C standard leaves int size flexible, POSIX-compatible UNIX/Linux systems enforce a 4-byte int via their ABIs, ensuring that file descriptor handling (including cmsghdr transfers) works reliably across compilers and processes.
内容的提问来源于stack exchange,提问作者Hauleth

