GCC Pipeline, Make & POSIX Types
Signed integer overflow checks silently deleted at -O2, strlen() truncating binary frames at 0x00, unsigned size_t wraparound on -1 errors, and decimal 644 permission literals cause catastrophic C bugs. You will master the four-stage GCC/ar pipeline, feature-test macros, POSIX boundary types, and ISO C11 Undefined Behavior defenses.
What you'll learn
- Build multi-file ISO C11 targets across GCC stages (
-E,-S,-c,ar rcs, link) with-Wall -Wextra -Werror. - Configure
_POSIX_C_SOURCEand_FILE_OFFSET_BITS=64before headers usingman 2andman 3interface contracts. - Audit C11 code for Undefined Behavior,
-fno-commoncollisions,size_t/ssize_twraparound, and octal0644bugs.
Why Sloppy C Types and Opaque Builds Break Systems Software
Consider a network packet validator written as if (payload_len + 16 < payload_len) return -1; where payload_len is a signed int, paired with size_t n = read(fd, buf, cap); and open(path, O_CREAT | O_WRONLY, 644). Under -O0 unit tests on small ASCII inputs, every line appears to work. Under -O2 in production, GCC deletes the signed-overflow check completely—allowing an attacker passing INT_MAX - 4 to allocate a 12-byte heap buffer for a 2 GiB copy—while a -1 read() failure wraps unsigned size_t n to 18,446,744,073,709,551,615 (SIZE_MAX), and decimal 644 stamps sticky bit 01204 (--w----r-T) onto disk!
Naive C habits fail because developers conflate hardware assembly behavior with the abstract machine specified by ISO/IEC 9899:2011 (ISO C11), rely on IDE build buttons that hide linker flags and archive ordering, and guess header contracts instead of reading manual sections. Writing reliable Ring 3 systems code requires deterministic command-line builds, exact POSIX boundary types, and zero tolerance for Undefined Behavior (UB).
note: Think of a precision machine shop with an assembly blueprint, calipers calibrated in millimeters versus signed tolerances, and standardized part bins. Reading the wrong scale or skipping the torque specification produces parts that look close on the bench and shear under load.
Where it stops working: Unlike physical tolerances that degrade gradually, mixing unsigned size_t with signed ssize_t -1 or decimal 644 with octal 0644 flips exact bits instantaneously.
definition (Four-Stage GCC Pipeline, Feature Macros & C11 UB): Four-Stage Translation Pipeline & Tentative Definitions: Originating in early Unix cpp -> cc1 -> as -> ld passes, GCC lowers ISO C11 source across preprocessing (-E -> .i), compilation (-S -> .s), assembly (-c -> relocatable Executable and Linkable Format .o), and linking (ar rcs static .a archives or -fPIC -shared .so objects). Feature-Test Macros (_POSIX_C_SOURCE, named by IEEE 1003.1 to gate namespace exposure) unlock POSIX declarations above ISO C11, while Undefined Behavior (UB, C11 §3.4.3) designates operations—such as signed overflow or strict-aliasing violations—for which the standard imposes zero requirements.
One Layer Down: ELF Object Sections, Alignment Math & Link Order
Across Stage 3 (gcc -c), the assembler partitions each relocatable .o file into distinct ELF sections: .text (machine instructions), .rodata (string literals and const tables), .data (initialized globals), .bss (Block Started by Symbol: zero-initialized globals occupying zero on-disk bytes), and .symtab + .rela.text relocation records. In ISO C11, writing int g_status; at file scope without extern is a tentative definition; GCC 10+ enables -fno-common by default, emitting a strong .bss definition in every .o that includes such a header and failing at link time with multiple definition. Declare extern int g_status; in .h headers, define it once in one .c file, and mark file-private helpers static (STB_LOCAL in nm / readelf -sW). Furthermore, the GNU linker resolves static .a archives in a single left-to-right pass, so gcc main.o -L. -lsysbuf succeeds whereas gcc -L. -lsysbuf main.o leaves main.o's symbols unresolved!
Struct layout and boundary sizing obey exact binary alignment arithmetic. Every scalar type of alignment A = 2^k bytes must start at a byte offset O satisfying O_aligned = (O + A - 1) & ~(A - 1). Inside struct padded_hdr { uint8_t tag; uint32_t seq; uint16_t flags; }, tag occupies byte 0, seq (A = 4) rounds offset 1 up to (1 + 3) & ~3 = 4 (inserting 3 padding bytes [1..3]), flags (A = 2) lands at byte 8, and total sizeof(struct padded_hdr) rounds 10 up to a multiple of max(A) = 4, yielding 12 bytes! Likewise, decimal 644 equals 512 + 128 + 4 = 01204 in octal, whereas octal 0644 equals 6 * 64 + 4 * 8 + 4 * 1 = 420 in base 10 (rw-r--r--).
| Type / Category | C11 / POSIX Specification | Exact Bit / Sign Contract & Engineering Rule |
|---|---|---|
size_t / ssize_t | Unsigned capacity vs signed return | size_t (%zu) sizes buffers; ssize_t (%zd) holds 0..SSIZE_MAX or -1 error |
off_t (_FILE_OFFSET_BITS=64) | Signed 64-bit byte coordinate | Addresses up to 2^63 - 1 (8 EiB) on both 64-bit x86-64 and 32-bit ARMv7 |
mode_t & uint8_t | Octal permission mask & raw byte | Write leading-zero 0644 (never 644); pass (const uint8_t *, len), never strlen() |
man 1 / man 2 / man 3 | Linux manual sections | 1 shell utilities, 2 Linux kernel syscalls, 3 glibc library functions |
| Implementation-Defined | Documented target ABI choice | Plain char is unsigned [0..255] on ARMv7 EABI vs signed [-128..127] on x86-64 |
Undefined Behavior (UB) | Unreachable on valid paths | Signed overflow (a + b < a folded to 0 at -O2), shift >= width, -fstrict-aliasing casts |
Figure 1.2. Four-stage GCC/archive builds, struct padded_hdr byte-alignment math, and signed/unsigned POSIX boundary contracts.
- Step 1. Stage 1 (-E) — Define _POSIX_C_SOURCE and _FILE_OFFSET_BITS=64 on lines 1..2 before any header is included.
- Step 2. Stage 2 (-S -O2) — Compile strict C11 to assembly; use unsigned subtraction so -O2 never deletes signed-overflow guards.
- Step 3. Stage 3 (-c & ar rcs) — Emit ELF .text/.rodata/.data/.bss sections under -fno-common and index static .a archives.
- Step 4. Stage 4 (ld + ASan/UBSan) — Place -lsysbuf after caller .o files and gate CI with -fsanitize=address,undefined.
Figure 1.2b. Feature-test macros, strict C11 warning/sanitizer flags, and single-pass archive link ordering eliminate silent type and symbol bugs at build time.
Feature-Test Macros,Incremental Make & Sanitizer Flags
Under strict -std=c11, GCC defines __STRICT_ANSI__ and hides POSIX symbols (fileno, pread, fdatasync, strnlen) inside <stdio.h> and <unistd.h> unless #define _POSIX_C_SOURCE 200809L and #define _FILE_OFFSET_BITS 64 appear before the very first #include in every translation unit. Pair -Wall -Wextra -Werror with -MMD -MP in GNU Make so header edits trigger automatic rebuilds, and run CI tests under AddressSanitizer and UndefinedBehaviorSanitizer (-fsanitize=address,undefined -fno-omit-frame-pointer).
learner@ksa:~/gl-c01/m01-l02$ bat -H 2 -H 9 -H 12 Makefile File: Makefile CC := gcc CFLAGS := -std=c11 -Wall -Wextra -Werror -MMD -MP -g -O2 SAN := -fsanitize=address,undefined -fno-omit-frame-pointer .PHONY: all sanitize clean all: inspector libsysbuf.a: sysbuf.o ar rcs $@ $^ inspector: inspector.o libsysbuf.a $(CC) $(CFLAGS) inspector.o -L. -lsysbuf -o $@ sanitize: sysbuf.c inspector.c $(CC) $(CFLAGS) $(SAN) inspector.c sysbuf.c -o inspector_san -include *.d clean: rm -f *.o *.d *.a inspector inspector_san- -MMD -MP emits .d header dependency rules so editing a .h struct layout rebuilds affected .o files automatically.
- ar rcs creates static archive libsysbuf.a and writes the symbol index table required by ld.
- Place -lsysbuf AFTER inspector.o so the single-pass linker resolves inspector.o's undefined references.
Auditing Binary Frames, Struct Padding, Strict Aliasing & Octal Modes
Save type_bridge.c below. It proves seven foundational systems C contracts in one sanitizer-clean binary: sizeof(raw_frame) (16) vs strlen() truncating at embedded 0x00 (2), array-to-pointer decay (sizeof(buf_ptr) == sizeof(void *)), unsigned subtraction capacity checks (safe_frame_fits), 64-bit off_t, octal 0644 (420) vs decimal 644 (01204), offsetof()/alignof() padding math, and -fstrict-aliasing-safe float -> uint32_t bit extraction via memcpy() (compiled to a single register move at -O2).
learner@ksa:~/gl-c01/m01-l02$ bat -H 1 -H 2 -H 23 -H 29 type_bridge.c File: type_bridge.c #define _FILE_OFFSET_BITS 64 #define _POSIX_C_SOURCE 200809L #include <stdalign.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> struct padded_hdr { uint8_t tag; uint32_t seq; uint16_t flags; }; static size_t pointer_sizeof(const uint8_t *buf_ptr) { return sizeof(buf_ptr); } static uint32_t pun_float_bits(float v) { uint32_t bits = 0U; memcpy(&bits, &v, sizeof(bits)); return bits; } static int safe_frame_fits(size_t payload, size_t hdr_sz, size_t cap) { return (hdr_sz <= cap) && (payload <= cap - hdr_sz); } int main(void) { const uint8_t raw_frame[16] = { 0x4BU, 0x53U, 0x00U, 0x41U, 0x10U, 0x20U, 0x30U, 0x40U }; size_t arr_bytes = sizeof(raw_frame); size_t cstr_len = strlen((const char *)raw_frame); size_t ptr_bytes = pointer_sizeof(raw_frame); mode_t oct_mode = 0644; mode_t dec_bug = 644; uint32_t fbits = pun_float_bits(1.0f); int ovf_rejected = !safe_frame_fits(SIZE_MAX - 4U, 12U, 4096U); printf("arr_sizeof=%zu strlen_at_nul=%zu ptr_decayed=%d ovf_guard=%d\n", arr_bytes, cstr_len, ptr_bytes != arr_bytes && ptr_bytes == sizeof(void *), ovf_rejected); printf("ssize_signed=%d off_bits=%zu oct_0644=%u dec_644_oct=0%o\n", (ssize_t)-1 < 0, sizeof(off_t) * 8U, (unsigned int)oct_mode, (unsigned int)dec_bug); printf("hdr_sz=%zu seq_off=%zu align=%zu f32_hex=0x%08x\n", sizeof(struct padded_hdr), offsetof(struct padded_hdr, seq), alignof(struct padded_hdr), fbits); return EXIT_SUCCESS; }- Feature-test macros MUST precede every #include so <features.h> exposes 64-bit off_t and POSIX.1-2008 prototypes.
- memcpy(&bits, &v, sizeof(bits)) extracts IEEE-754 bits legally under C11 -fstrict-aliasing and compiles to zero memory traffic at -O2.
- Unsigned subtraction cap - hdr_sz avoids signed integer overflow UB that GCC -O2 would fold away.
Stepping Through All Four GCC Stages, nm & Sanitizers
Execute all four GCC translation stages (-E, -S, -c, and final link with -fsanitize=address,undefined), inspect symbol visibility in type_bridge.o with nm (t local static helpers vs T global main), and verify ./type_bridge.
learner@ksa:~/gl-c01/m01-l02gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror -E type_bridge.c -o type_bridge.ilearner@ksa:~/gl-c01/m01-l02gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror -S type_bridge.c -o type_bridge.slearner@ksa:~/gl-c01/m01-l02gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror -c type_bridge.c -o type_bridge.olearner@ksa:~/gl-c01/m01-l02nm type_bridge.o | grep -c ' T main$'1learner@ksa:~/gl-c01/m01-l02gcc -fdiagnostics-color=always -std=c11 -O2 -Wall -Wextra -Werror -fsanitize=address,undefined type_bridge.c -o type_bridgelearner@ksa:~/gl-c01/m01-l02./type_bridge && rm -f type_bridge.i type_bridge.s type_bridge.o type_bridgearr_sizeof=16 strlen_at_nul=2 ptr_decayed=1 ovf_guard=1ssize_signed=1 off_bits=64 oct_0644=420 dec_644_oct=01204hdr_sz=12 seq_off=4 align=4 f32_hex=0x3f800000learner@ksa:~/gl-c01/m01-l02Why Strict Types, Visibility & Sanitizers Catch Silent Corruption
Stepping across .i -> .s -> .o -> ELF proved each layer's contract empirically. In type_bridge.o, nm reported main as T (STB_GLOBAL in .text) while static helpers stayed module-private so they cannot collide across .o files. At runtime under ASan + UBSan, raw_frame occupied 16 stack bytes while strlen() stopped at raw_frame[2] == 0x00 (2), pointer_sizeof() confirmed array-to-pointer decay (8 bytes on 64-bit), struct padded_hdr measured 12 bytes (seq_off=4, align=4), safe_frame_fits() blocked SIZE_MAX - 4U + 12U wraparound without UB, and memcpy() extracted 0x3f800000 (1.0f) cleanly.
Guided Practice: Reordering Struct Fields & Fixing Aliasing UB
Examine struct padded_hdr (12 bytes: uint8_t tag; uint32_t seq; uint16_t flags;) and the broken strict-aliasing cast uint32_t bad = *(uint32_t *)&float_val;:
- Step 1 (Eliminate internal padding): Reorder the three members of
struct padded_hdrfrom largest alignment (uint32_t) to smallest (uint8_t) without adding non-portable__attribute__((packed))(which causes unaligned bus faults on strict ARM hardware), and compute the newsizeof(struct compact_hdr)(8bytes) using the alignment formula above. - Step 2 (Verify with
_Static_assert): Add_Static_assert(sizeof(struct compact_hdr) == 8, "compact layout");in a local copy oftype_bridge.c, replace any pointer-cast punning withmemcpy(), and confirmgcc -std=c11 -O2 -Wall -Wextra -Werrorexits0.
Independent Practice: Static Archive Link-Order & -fno-common Audit
Create three files (frame.h, frame.c, driver_cli.c) where frame.h declares extern size_t g_frames_encoded; and size_t encode_u32_be(uint8_t *dst, size_t cap, uint32_t val); (writing big-endian bytes via unsigned shifts val >> 24, (val >> 16) & 0xFFU, etc.). Archive frame.o into libframe.a via ar rcs, confirm nm -g libframe.a lists encode_u32_be and g_frames_encoded, verify that wrong link order (gcc -L. -lframe driver_cli.o) fails while gcc driver_cli.o -L. -lframe succeeds, and run under -fsanitize=address,undefined.
Common Production Pitfalls
warning: Symptom: GCC rejects fileno(), pread(), or strnlen() with implicit declaration of function under -std=c11 -Werror even though #define _POSIX_C_SOURCE 200809L is present in the .c file. Root Cause: A project header (such as #include "config.h") included <stdio.h> above the #define, freezing <features.h> in strict ISO C11 mode for the rest of the translation unit. Fix: Place #define _POSIX_C_SOURCE 200809L and #define _FILE_OFFSET_BITS 64 on lines 1–2 of every .c file (or pass -D_POSIX_C_SOURCE=200809L -D_FILE_OFFSET_BITS=64 in CFLAGS).
warning: Symptom: A length guard if (signed_len + hdr_sz < signed_len) return -1; passes -Wall -Wextra cleanly yet allows heap corruption at -O2, or int status; inside common.h triggers multiple definition of 'status' on GCC 13. Root Cause: Signed integer overflow is ISO C11 Undefined Behavior so -O2 folds a + 16 < a to false, and GCC 10+ defaults to -fno-common so tentative definitions in headers emit colliding .bss globals. Fix: Validate capacities via unsigned size_t subtraction (if (len > cap - hdr_sz)), and declare extern int status; in headers with exactly one .c definition.
Knowledge Check
Key takeaways
- Compile multi-file systems C projects explicitly across preprocessing (
-E), compilation (-S), assembly (-c), archiving (ar rcs), and linking with-std=c11 -Wall -Wextra -Werrorand-fsanitize=address,undefined. - Define feature-test macros (
_POSIX_C_SOURCE 200809L,_FILE_OFFSET_BITS 64) before the very first#include, and useexterndeclarations in headers so GCC-fno-commonnever hits tentative-definition collisions. - Consult
man 2for Linux kernel syscalls andman 3forglibcfunctions, verifyingSYNOPSIS,RETURN VALUE, andERRORSbefore writing callers. - Pair unsigned
size_tcapacities with signedssize_t/off_treturn checks, pass(const uint8_t *, len)for binary data, write octal0644permissions, and replace signed-overflow or pointer-aliasing UB with unsigned subtraction andmemcpy(). - Next, we will link C11 translation units against
glibc(libc.so.6), trace dynamic.plt/.got.pltrelocations and C Runtime (CRT)_startinitialization, inspecterrno, and count exact traps understrace.