
Recall first from Bitfields, portable formats, and classic mistakes
- Use uintN_t and inttypes.h macros for anything that crosses a wire, file, or register boundary.
- Struct bitfields have implementation-defined layout, so use masks and fixed-width types for registers, files, and wire formats.
- The idiom v & (v - 1) clears the lowest set bit and tests for a power of two; popcount is reached with __builtin_popcount.
Why programs are split into files
2 min readSo far every program in this module has fit in a single .c file, built to teach the C language. This lesson answers how a program split across many files is compiled and linked into one executable.
So far every program in this module has fit in a single .c file. Real systems programs do not. A device driver, a filesystem tool or an operating system has thousands of functions spread across hundreds of files. You never compile them as one giant blob; you compile each .c file on its own and then combine the results. This is separate compilation, the practice of compiling each source file independently into its own object file and then linking those objects into one program, and it is the foundation everything in this lesson builds on.
Separate compilation earns its keep in four ways. First, structure: a program becomes a set of small modules, each with one clear job, instead of a single wall of code. Second, speed of rebuild: when you change one file, you recompile only that file and relink, instead of recompiling everything. On a project with hundreds of files this is the difference between seconds and minutes of build time. Third, reuse: a module such as a ring buffer or a sensor driver can be compiled once and linked into many programs, exactly the way the C standard library is written once and linked into everything. Fourth, collaboration: two engineers can own different files and edit them at the same time without stepping on each other.
The cost is a new kind of bookkeeping. Once a name lives in one file and is used in another, you have to tell the compiler and the linker about it. That bookkeeping, declarations, headers, linkage and the build system that automates the whole thing, is the subject of this lesson. By the end you will be able to build a multi-file program by hand and with make, and to explain every error the toolchain throws at you along the way.
The previous lessons built single-file programs to teach the language. This lesson turns those skills into a real engineering workflow. Everything you will meet in later modules, the Linux kernel, U-Boot, Buildroot, Yocto, xv6, is built this way: many files, separate compilation, and a build system that tracks dependencies.
A short history of separate compilation and make
3 min readSeparate compilation is older than C. The first FORTRAN compiler, delivered in 1957, already produced relocatable object files that a separate loader combined, and assemblers had done the same for machine code before that. The idea is simple: translate one piece of source into machine code that still has holes in it, note where the holes are, and fill them in later when every piece is present.
When C was created at Bell Labs in the early 1970s, this became a pipeline of small tools rather than one monolithic compiler. A preprocessor (traditionally cpp) expands directives such as #include and #define; the compiler proper (cc1) turns the preprocessed source into assembly; the assembler (as) turns that into an object file; and the linker (ld) combines object files into an executable. The gcc command you type is a driver that runs these stages in order and hides them from you.
Early K&R C was loose about declarations. A function could be called without any prior declaration, and the compiler silently guessed its return type, an implicit function declaration. Old-style function definitions wrote the parameter names before the braces and the types after them, as in int add(x, y) int x, y; { return x + y; }. The first ANSI standard, C89, standardized function prototypes, and the linkage model we still use today, where extern announces a name and static hides one. C99 removed implicit function declarations from the language, and C23, published in 2024, finally removed old-style definitions too. Compilers kept accepting the old code for compatibility: GCC 13 on Ubuntu 24.04 still only warns "implicit declaration of function", while GCC 14 and later reject it as an error.
On top of this toolchain sits make, written by Stuart Feldman at Bell Labs in 1976. make's job is to recompile only what changed. You give it a set of rules describing how to build each file and which files depend on which, and make walks that graph, comparing file timestamps, and reruns only the rules whose outputs are older than their inputs. That one idea, a build graph driven by timestamps, is still how enormous systems are built today, and make remains the default build tool for the Linux kernel and U-Boot.
Explore the same turning points on an interactive timeline:
Why does this history matter to a systems engineer? Because the errors you will see, undefined reference, multiple definition, redefinition, are consequences of decisions made decades ago about how names cross file boundaries. Understanding the model behind the toolchain is what lets you read those errors as information instead of noise.
Translation units and the linker
4 min readA a source file together with every header and source line pulled in by #include, after conditional compilation is applied, which the compiler turns into one object file is the unit of compilation in C. When you run gcc -c sensor.c, the compiler reads sensor.c, expands every #include it contains, and produces one a file of machine code plus symbol and relocation tables, produced from one translation unit and not yet a runnable program, by convention named sensor.o. It knows nothing about main.c or stats.c, and it does not need to.
The compiler can get away with this because of a division of labour. When one file calls a function defined in another, the compiler does not need the function's body. It needs only the function's signature, its return type and parameter types, so it can generate a correct call. The call site becomes an unresolved reference, a a name that refers to a function or a global variable, which the linker must locate and connect to its uses, recorded in the object file. The the program, typically ld, that combines object files and libraries into one executable and resolves every symbol reference to its definition then takes all the object files, finds the definition of every symbol that was referenced, and patches the addresses in. This whole pass is called linking.
Because each file compiles alone, a symbol defined in sensor.c and used in main.c is fine, as long as the linker can find it. When it cannot, you get the classic a linker error reporting that a symbol was used but no object or library provided its definition. When two files both define the same global name, you get the other classic error, a duplicate definition. Both are linker errors, which is the first clue: the compiler was satisfied, and the failure happened when everything came together.
Preprocess: the driver runs the preprocessor, expanding includes and macros in each .c file into a single stream of text.
Compile: the compiler proper translates each preprocessed translation unit into assembly for the target machine.
Assemble: the assembler turns each assembly file into an object file, machine code plus symbol and relocation tables.
Link: the linker reads every object file and library, resolves each undefined symbol to its definition, and emits one executable.
Let us see the two failures. Imagine main.c calls a function average that is declared in a header, but you forget to compile stats.c where average is defined. The compile step succeeds, and the link step fails.
$ gcc main.o sensor.o -o monitor
/usr/bin/ld: main.o: in function `main':
main.c:(.text+0x2f): undefined reference to `average'
collect2: error: ld returned 1 exit status
This is typical output, and yours will differ in the offset and address. The important part is the message: the linker found a use of average and no definition. The opposite failure is defining the same global in two files, which we return to in the next section.
The gdb lesson in this module used single-file programs, but nothing changes for a multi-file program: you build with -g, then set breakpoints in any file, because after linking, gdb maps every address back to the source file that produced it.
learner@embeddex:~/lab$ # each .c is a translation unit, compiled alone into an object file learner@embeddex:~/lab$ gcc -c main.c learner@embeddex:~/lab$ # sensor.c compiles without knowing main.c exists learner@embeddex:~/lab$ gcc -c sensor.c learner@embeddex:~/lab$ # so does stats.c, which defines average learner@embeddex:~/lab$ gcc -c stats.c learner@embeddex:~/lab$ # three object files, one per translation unit learner@embeddex:~/lab$ ls *.o main.o sensor.o stats.o learner@embeddex:~/lab$ # forget stats.o and the compiler is satisfied; the linker is not learner@embeddex:~/lab$ gcc -o monitor main.o sensor.o /usr/bin/ld: main.o: in function `main': main.c:(.text+0x45): undefined reference to `average' collect2: error: ld returned 1 exit status learner@embeddex:~/lab$ # add the missing object and the undefined reference disappears learner@embeddex:~/lab$ gcc -o monitor main.o sensor.o stats.o learner@embeddex:~/lab$ # the linked program runs learner@embeddex:~/lab$ ./monitor avg=20 reading=7
Headers, prototypes, declarations and definitions
4 min readA a statement that introduces a name and its type to the compiler without reserving storage for it announces what exists. A a declaration that also reserves storage, or provides a function's body, creating the entity itself creates it. For a function, int average(int *v, int n); is a declaration, and int average(int *v, int n) { ... } is a definition. For a global variable, extern int samples_taken; is a declaration, while int samples_taken; is a definition.
A header, a file by convention ending in .h that several source files include to share the same declarations, is how declarations travel between files. Every file that calls a function or reads a global needs its declaration before use, and copying the same prototype into ten files invites drift. The fix is to put the declaration in one header and include it everywhere. The header is a contract, and including it in both the file that defines the function and the file that calls it means the compiler checks both sides against the same text.
/* sensor.h */
#ifndef SENSOR_H
#define SENSOR_H
int sensor_read(void);
extern int samples_taken;
#endif
The #ifndef/#define/#endif wrapper is an a preprocessor pattern that ensures a header's contents are processed only once, even if it is included several times. It works by defining a macro the first time through and skipping the body on every later inclusion. Without it, two headers that include each other, or one header included twice, produces redefinition errors.
1guard it
Wrap the whole file in an include guard named after the header, such as SENSOR_H, never with a leading underscore.
2declare only
Put function prototypes and extern variable declarations in the header, never definitions.
3define in one .c
The matching sensor.c defines the function and, once, the global variable.
4include what you use
Each .c includes the headers for the names it directly uses, no more and no less.
5include the header in its own .c
sensor.c includes sensor.h so the compiler verifies the definitions match the prototypes.
The distinction between declaration and definition has a hard consequence called the the rule that a program may have exactly one definition of each function and each global variable, though it may have many declarations. Defining the same function in two object files, or defining the same global in two files, makes the linker fail with a duplicate-definition error.
$ gcc main.o sensor.o stats.o -o monitor
/usr/bin/ld: stats.o: in function `average':
stats.c:(.text+0x0): multiple definition of `average'; sensor.o: ...
collect2: error: ld returned 1 exit status
The most common way to violate the rule is putting a definition in a header. If stats.h contains int samples_taken;, every file that includes it gets its own definition, and the linker sees duplicates.
A header should contain only declarations. If two or more files need to share a global, declare it extern in the header and define it exactly once in a single .c file. The one-definition rule is enforced by the linker, not the compiler, so the mistake surfaces only at link time.
Before prototypes, C used implicit declarations and old-style definitions. In int add(x, y) int x, y; { return x + y; }, the compiler sees the body before it knows the parameter types, so it cannot check that callers pass the right types. A prototype fixes this by declaring the types up front. Always declare a function before calling it, and never write an old-style definition: implicit declarations left the language in C99 and old-style definitions in C23. Compile with -Werror=implicit-function-declaration so GCC 13 stops treating the first as a mere warning.
learner@embeddex:~/lab$ # a variable definition in a header: every includer gets its own copy learner@embeddex:~/lab$ cat config.h int version = 3; learner@embeddex:~/lab$ # each file compiles happily on its own learner@embeddex:~/lab$ gcc -c a.c learner@embeddex:~/lab$ # the compiler never sees the other file's copy learner@embeddex:~/lab$ gcc -c b.c learner@embeddex:~/lab$ # the linker sees two definitions of version and stops learner@embeddex:~/lab$ gcc -o demo a.o b.o /usr/bin/ld: b.o:(.data+0x0): multiple definition of `version'; a.o:(.data+0x0): first defined h ere collect2: error: ld returned 1 exit status learner@embeddex:~/lab$ # fix: declare extern in the header, defining nothing learner@embeddex:~/lab$ printf 'extern int version;\n' > config.h learner@embeddex:~/lab$ # and define it exactly once, here in a.c learner@embeddex:~/lab$ printf 'int version = 3;\n' >> a.c learner@embeddex:~/lab$ # recompile and link: one definition satisfies both references learner@embeddex:~/lab$ gcc -c a.c && gcc -c b.c && gcc -o demo a.o b.o learner@embeddex:~/lab$ # it runs; the exit code 3 is the value of version learner@embeddex:~/lab$ ./demo; echo $? 3
Key takeaways
- Each .c file is a translation unit compiled alone into an object file; the linker stitches them and resolves symbols.
- A declaration announces a name; a definition also reserves storage, and each name may have exactly one definition.
- Headers carry declarations and include guards, never variable definitions, and each file includes only what it uses.
- Compilation is a pipeline of small tools, the preprocessor, compiler, assembler and linker, and gcc drives them in order.
Reflect
- Explain to a colleague, in two sentences: explain why large C programs are split into translation units and what the linker contributes.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- SpecificationC standard draft N1570 (ISO/IEC 9899:2011), translation units and linkage
- Man pagegcc(1) man page
Official documentation first. Links checked when the lesson was published.