C++ Reference ยท Preprocessor, Tools and Concepts
Compiling and linking in C++
How C++ builds a program: translation units, declarations versus definitions, internal and external linkage, the ODR, static and shared libraries.
A C++ program is built in stages. The preprocessor expands #include and macros, the compiler turns each source file (a translation unit) into an object file, and the linker joins object files and libraries into an executable. Each translation unit is compiled alone, so it can only see what its includes declared: the linker is the stage that connects a call to the single definition somewhere else.
Almost every confusing build error comes from this split. "Undefined reference" is a linker error: a name was declared but no definition was found. "Multiple definition" is the opposite: two translation units both defined it. The rule that governs both is the One Definition Rule (ODR).
g++ -c main.cpp -o main.o # compile one translation unit g++ -c util.cpp -o util.o g++ main.o util.o -o app # link
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.
Our runner compiles a single file, so it cannot reproduce multi-file errors. The next section shows what they look like.
Declaration versus definition
A declaration introduces a name and its type. A definition also creates the entity: it allocates storage or provides a function body.
extern int total; // declaration (no storage) int total = 0; // definition void log(const char*); // declaration void log(const char* m) { /* ... */ } // definition
Headers should contain declarations, inline functions and variables, templates, constexpr functions, and class definitions. One .cpp file should hold the definition of every other function and variable.
Typical link errors
undefined reference to `next_id()' // declared and used, but no definition was linked multiple definition of `helper()' // defined in a header without inline, included twice undefined reference to `vtable for Shape' // a virtual function was declared but never defined
The first usually means a missing .cpp file or library on the link line. The second means a header defines something it should only declare or mark inline. The third means a class with virtual functions lacks the definition of its first non-inline virtual function (the key function).
The One Definition Rule
Within one program, every non-inline function and variable has exactly one definition. Classes, inline functions and templates may be defined in many translation units, but the definitions must be token-for-token equivalent and mean the same thing in each. Violations are "ill-formed, no diagnostic required": the compiler and linker may not complain, and you get silent bugs. A typical cause is compiling two files with different -D macros or different standards, so the same class has a different layout in each file.
Linkage
- External linkage: the name can be used from other translation units. This is the default for non-
constnamespace-scope functions and variables. - Internal linkage: visible only in this file. Use an unnamed namespace (preferred) or
static. Namespace-scopeconstandconstexprvariables are internal by default. - No linkage: local variables and local classes.
- Module linkage: names exported by C++20 modules (read-only on our runner; see import and module).
extern "C": gives a function C linkage and an unmangled name, so it can be called from C or a plugin loader. C++ normally mangles names to encode overloads and namespaces.
Libraries
| Kind | Linux | Windows | Properties |
|---|---|---|---|
| Static | libfoo.a (made with ar) |
foo.lib |
Copied into the executable at link time. No runtime dependency. |
| Shared | libfoo.so |
foo.dll (+ import library) |
Loaded at start-up or on demand. Can be updated separately, and shared between processes. |
g++ -c util.cpp ar rcs libutil.a util.o # static library g++ main.cpp -L. -lutil -o app # link it (library after the files that need it) g++ -fPIC -shared util.cpp -o libutil.so # shared library
Usage notes
- Put definitions that must be shared in headers only if they are
inline, templates orconstexpr. Everything else goes into one.cpp. - Use unnamed namespaces for file-private helpers. They cannot collide with a helper of the same name in another file.
- A static library is searched in order. On Linux, the linker takes only objects it needs, so list libraries after the objects that use them.
- Static initialization order across files is unspecified. A global in one file must not use a global defined in another during its own initialization. Use a function-local
staticinstead. - Templates need their definition at the point of use, usually in the header. Explicit instantiation (
template class Foo<int>;) in one.cppplusextern templateelsewhere reduces compile time. - Mismatched standard libraries or ABIs (different
-std=,-D_GLIBCXX_USE_CXX11_ABI, or debug versus release on MSVC) cause confusing link or crash bugs when you mix libraries.