Linking
Linking is the final build stage that matches every symbol a compiled object file references against a definition somewhere else, then patches the addresses so the pieces form one runnable program.
Detailed Explanation
An object file is not runnable. It contains machine code with holes in it. Where the code calls printf, the assembler could not know the address, so it left a placeholder and a note: "this spot needs the address of printf". Those notes are relocation entries, and the object file also carries a symbol table listing what it defines and what it merely references.
The linker does two jobs. Symbol resolution pairs each reference with exactly one definition, searching the other object files and then the libraries you named. Relocation then assigns final addresses to all the code and data and fills in every placeholder with the real number. The output is an executable or a shared library.
Only two things can go wrong, and both error messages are worth learning to read.
undefined reference to 'foo' means some object file referenced foo and the linker never found a definition. In practice the cause is one of: you declared the function but never wrote it; you wrote it in a .c file you forgot to add to the link command; you spelled it differently; or it lives in a library you did not pass with -l. The most common beginner version is calling sqrt and forgetting -lm, because on most Unix systems the maths functions live in a separate library from the rest of the C library.
multiple definition of 'bar' means two object files both define bar with external linkage. The usual cause is a global variable defined in a header file, so every .c that includes the header gets its own definition. The fix is to declare it in the header with extern and define it in exactly one .c file.
Libraries come in two shapes.
- A static library (
libfoo.a) is an archive of object files. The linker pulls in only the members that satisfy an outstanding reference and copies that code into your executable. The result is self-contained and larger. - A shared library (
libfoo.so,.dylibon macOS) is linked by reference. The executable records that it needslibfoo.so, and the dynamic loader finds and maps it at start-up. The executable stays small, several programs share one copy in memory, and the library can be patched without rebuilding you. The cost is that the file must be present and compatible at run time.
Link order matters, and this surprises nearly everyone. A traditional linker processes its inputs left to right, keeping a running set of unresolved symbols. When it reaches -lfoo it takes only what is needed at that moment. So cc -lm main.o can fail while cc main.o -lm succeeds: in the first command, nothing needed sqrt yet when the maths library went by. Put your object files first and your libraries after, and order libraries so that a library comes after everything that uses it. Circular dependencies between static libraries sometimes need a library listed twice, or -Wl,--start-group.
Code Examples
/* config.h — the correct pattern for a shared global.
* Declaration only, so every including TU sees the name
* but nobody creates an object for it here. */
#ifndef CONFIG_H
#define CONFIG_H
extern int verbose_level; /* declaration: "this exists somewhere" */
void set_verbose(int level);
#endif /* CONFIG_H *//* config.c — the single definition.
* cc -c config.c -c main.c
* cc config.o main.o -o app
*/
#include "config.h"
int verbose_level = 0; /* definition: exactly one in the whole program */
void set_verbose(int level)
{
verbose_level = level;
}
/* If config.h had said "int verbose_level;" instead of the extern form,
every .c that included it would define the symbol, and the link would
fail with: multiple definition of 'verbose_level' *//* distance.c — a function from libm, which is not linked by default.
* cc distance.c -o distance -lm works: object first, library after
* cc -lm distance.c -o distance may fail: nothing needed sqrt yet
*/
#include <math.h>
#include <stdio.h>
int main(void)
{
double dx = 3.0, dy = 4.0;
printf("%.1f\n", sqrt(dx * dx + dy * dy)); /* prints: 5.0 */
return 0;
}Common Gotchas
A declaration is a promise, not a definition
declaring `void flush_cache(void);` and never writing a body compiles fine in every TU and fails only at link time. The error names the *referencing* location, not the missing file, so read it as "who wanted this" and then ask what should have provided it.
Static library order is left to right
list libraries after the objects that use them, and after other libraries that depend on them. Shared libraries are more forgiving on some platforms, which is why the bug appears only when someone switches to a static build.
Linking succeeds against a stale object file
the linker checks names, not types or struct layouts. If you change a `struct` in a header and rebuild only some translation units, the link still works and the program reads fields at the wrong offsets. That is undefined behavior. Rebuild everything that includes the header.
A shared library must be findable at run time, not only at link time
`error while loading shared libraries` is the loader complaining, long after the build passed. Fix it with an `rpath` baked in at link time rather than by exporting `LD_LIBRARY_PATH` in each shell.