Skip to content
binshelf/ cpp

Search lessons

Type a C++ term, like vector, reference, unique_ptr or use-after-free.

    Lessons

    On this page

    1. Key terms
    2. In 30 seconds
    3. Splitting a program into files
    4. Including a header twice
    5. Namespaces: keeping names apart
    6. The one-definition rule
    7. inline: definitions in a header
    8. extern: the older way to share a variable
    9. Internal linkage: helpers private to one file
    10. Which one should I use?
    11. Under the hood
    12. Common pitfalls
    13. Defining a function outside its namespace
    14. Defining a template in a source file
    15. Try it yourself

    Module 8 · Organizing a project

    8.1Headers, source files and the one-definition rule

    Split a program into headers and source files, keep names apart with namespaces, and fix the two link errors every multi-file project meets: a definition that's missing, and one that's there twice.

    About 25 minutesIntermediate

    On this page
    1. Key terms
    2. In 30 seconds
    3. Splitting a program into files
    4. Including a header twice
    5. Namespaces: keeping names apart
    6. The one-definition rule
    7. inline: definitions in a header
    8. extern: the older way to share a variable
    9. Internal linkage: helpers private to one file
    10. Which one should I use?
    11. Under the hood
    12. Common pitfalls
    13. Defining a function outside its namespace
    14. Defining a template in a source file
    15. Try it yourself

    Key terms

    translation unit
    One source file after the preprocessor has pasted in its headers. The compiler works on one translation unit at a time and knows nothing about the others.
    include guard
    Lines that stop a header from being pasted into one translation unit twice: #pragma once at the top, or #ifndef, #define and #endif around the whole header.
    namespace
    A named group of declarations, such as std or dna. From outside, you reach a name in it with ::, as in dna::count_gc.
    one-definition rule (ODR)
    Each ordinary function and global variable that the program uses is defined exactly once in the whole program. Types, templates and inline functions may be defined in every translation unit that uses them, if every copy is the same.
    inline
    On a function or a variable: it may be defined in several translation units, and the linker keeps one. This lets you define it in a header.
    linkage
    Whether a name in one translation unit means the same thing in others. External linkage: shared by the whole program. Internal linkage: private to its own file.
    unnamed namespace
    namespace { … } in a source file. Everything inside has internal linkage, so other files can't see it or clash with it.
    extern
    On a global variable without an initializer: a declaration only. It says the variable is defined in another source file.

    A program in one file stops being comfortable at a few hundred lines. Splitting it into several files lets you find things, reuse them in other programs and rebuild only what changed. C++ does this with headers and source files, held together by one rule: every function has exactly one definition. This lesson shows how to split a program, and how to read the two link errors you get when the rule is broken.

    In 30 seconds

    • A header (dna.h) holds declarations; a source file (dna.cpp) holds the definitions. Every file that uses the functions includes the header.
    • Start every header with #pragma once, so including it twice does no harm.
    • Put your names in a namespace (dna::count_gc) so they can’t clash with anyone else’s.
    • An ordinary function defined in a header that two files include gives multiple definition; a declaration with no definition gives undefined reference. Functions defined in headers are marked inline.

    Splitting a program into files

    How a C++ program is built built a program from two source files, with the declaration typed out in main.cpp. A real project writes each declaration once, in a header, and includes it wherever it’s needed:

    3 files, built together

    dna.h
    #pragma once
    
    #include <string_view>
    
    int count_gc(std::string_view sequence);
    double gc_percent(std::string_view sequence);
    dna.cpp
    #include "dna.h"
    
    int count_gc(std::string_view sequence) {
        int count = 0;
        for (char base : sequence) {
            count += base == 'G' || base == 'C'; // true adds 1
        }
        return count;
    }
    
    double gc_percent(std::string_view sequence) {
        return 100.0 * count_gc(sequence) / static_cast<double>(sequence.size());
    }
    main.cpp
    #include <print>
    
    #include "dna.h"
    
    int main() {
        std::println("{} {:.1f}%", count_gc("GATTACA"), gc_percent("GATTACA"));
    }

    Build and run

    g++ -std=c++23 -Wall -Wextra -Wpedantic dna.cpp main.cpp -o app
    ./app

    Output

    2 28.6%
    • dna.h is the promise: these two functions exist, with these types. It includes <string_view> because its declarations use it: a header includes what it uses.
    • dna.cpp keeps the promise. It includes its own header, so the compiler sees each declaration before its definition.
    • main.cpp includes the header and calls the functions. It never sees their bodies.

    Each source file, with its headers pasted in, is a translation unit. The compiler turns each one into an object file on its own, knowing nothing about the others; the linker then connects each call in main.o to its definition in dna.o.

    The two #include spellings search different places. With GCC and Clang, a header in quotes is looked for first in the folder of the file doing the including, then where angle brackets look: the standard library’s folders and any you add with -I (g++ -I include …). Use quotes for your project’s headers, and angle brackets for the standard library and installed libraries. CMake and libraries adds the -I folders for you.

    Including a header twice

    Headers include other headers, so one header can reach a translation unit by two routes: main.cpp includes read.h, and also quality.h, which includes read.h too. Declaring a function twice is harmless, but if read.h defines a struct, main.cpp now holds that definition twice, which is a compile error.

    An include guard prevents it. The modern one is #pragma once on a header’s first line, as in dna.h above: the preprocessor pastes the file into a translation unit once, and skips it after that. The older one, which you’ll see in many libraries, wraps the whole header in #ifndef, #define and #endif; the dna.h in the one-definition rule section below uses it.

    Namespaces: keeping names apart

    Every name at the top level of a program shares one space, so two parts of a project, or two libraries, that both define count(std::string_view, char) clash. A namespace gives names a surname:

    #include <algorithm>
    #include <print>
    #include <string_view>
    
    namespace dna {
    
    int count(std::string_view sequence, char base) {
        return static_cast<int>(std::ranges::count(sequence, base));
    }
    
    } // namespace dna
    
    namespace protein {
    
    int count(std::string_view sequence, char residue) {
        return static_cast<int>(std::ranges::count(sequence, residue));
    }
    
    } // namespace protein
    
    int main() {
        std::println("{}", dna::count("GATTACA", 'A'));
        std::println("{}", protein::count("MKTAYIA", 'A'));
        using dna::count;
        std::println("{}", count("GATTACA", 'T'));
    }

    Output

    3
    2
    2
    • namespace dna { … } puts everything inside into dna. Outside, you write dna::count, just as std::println is the println in std. The comment after the closing brace helps in long files.
    • using dna::count; lets you write plain count for the rest of that block.
    • Namespaces nest: namespace bio::dna { … } opens dna inside bio, and outside code writes bio::dna::count.
    • A namespace can be opened again in another file, and the names add up. That’s how one dna namespace spreads over dna.h and dna.cpp.

    Never write using namespace std; (which makes every name in std usable without std::) in a header. It does that to every file that includes the header, and their own names, such as a global count, suddenly clash with std::count. In a .cpp file, using affects only that file.

    The one-definition rule

    The one-definition rule (ODR) says each ordinary function and global variable that the program uses has exactly one definition in the whole program. Each object file is fine on its own, so only the linker sees a break, and it reports one of two errors. No definition gives undefined reference, which you met in How a C++ program is built (Common pitfalls shows a new way to cause it). Two definitions give multiple definition.

    count_gc is short, so someone moved its body into the header. dna.cpp and main.cpp both include it, so both object files define count_gc:

    3 files, built together

    dna.h
    #ifndef DNA_H
    #define DNA_H
    
    #include <string_view>
    
    int count_gc(std::string_view sequence) {
        int count = 0;
        for (char base : sequence) {
            count += base == 'G' || base == 'C';
        }
        return count;
    }
    
    double gc_percent(std::string_view sequence);
    
    #endif
    dna.cpp
    #include "dna.h"
    
    double gc_percent(std::string_view sequence) {
        return 100.0 * count_gc(sequence) / static_cast<double>(sequence.size());
    }
    main.cpp
    #include <print>
    
    #include "dna.h"
    
    int main() {
        std::println("{} {}", count_gc("GGCA"), gc_percent("GGCA"));
    }

    Build and run

    g++ -std=c++23 -Wall -Wextra -Wpedantic dna.cpp main.cpp -o app
    ./app

    The compiler rejects this

    ld: in function `count_gc(std::basic_string_view<char, std::char_traits<char> >)':
    main.cpp: multiple definition of `count_gc(std::basic_string_view<char, std::char_traits<char> >)'; dna.cpp: first defined here
    collect2: error: ld returned 1 exit status

    This header has the older include guard. #ifndef DNA_H means “if DNA_H isn’t defined yet”: the first time, it isn’t, so the next line defines it and the rest is pasted in; any later time, the preprocessor skips to #endif. The guard’s name must be unique in the whole project, which is why #pragma once, with no name, is easier.

    Neither kind of guard helps here: a guard works inside one translation unit, and here there are two. Either move the body back into dna.cpp, as in the first example, or mark the function inline.

    Undefined behaviorTwo different definitions of one type

    Types may be defined in every translation unit, so the linker doesn’t compare them. If two source files each define their own struct Read with different members, the program breaks the ODR with no error at all. That’s undefined behavior: code from one file can read the other file’s objects with the wrong layout. Define each type once, in a header.

    inline: definitions in a header

    An inline function may be defined in every translation unit that includes it, as long as every copy is the same; the linker keeps one. Since C++17 the same works for a global variable: an inline variable is one object, shared by every file.

    3 files, built together

    dna.h
    #pragma once
    
    #include <string_view>
    
    namespace dna {
    
    inline int reads_seen = 0;
    
    inline int count_gc(std::string_view sequence) {
        ++reads_seen;
        int count = 0;
        for (char base : sequence) {
            count += base == 'G' || base == 'C';
        }
        return count;
    }
    
    double gc_percent(std::string_view sequence);
    
    } // namespace dna
    dna.cpp
    #include "dna.h"
    
    double dna::gc_percent(std::string_view sequence) {
        return 100.0 * count_gc(sequence) / static_cast<double>(sequence.size());
    }
    main.cpp
    #include <print>
    
    #include "dna.h"
    
    int main() {
        std::println("{}", dna::count_gc("GATTACA"));
        std::println("{:.1f}%", dna::gc_percent("GGCC"));
        std::println("reads seen: {}", dna::reads_seen);
    }

    Build and run

    g++ -std=c++23 -Wall -Wextra -Wpedantic dna.cpp main.cpp -o app
    ./app

    Output

    2
    100.0%
    reads seen: 2

    count_gc runs once from main.cpp and once from dna.cpp, and both add to the same reads_seen. dna.cpp defines gc_percent by its full name, dna::gc_percent; that only compiles if the header declares a matching function, so a typo becomes a compile error right there.

    Some things are inline without the word, and live in headers for the same reason: the compiler needs the whole body in every file that uses them.

    • constexpr functions, which the compiler may run while compiling any file (constexpr and consteval).
    • Member functions defined inside their class body.
    • Templates aren’t inline, but follow the same rule: to make larger<int>, the compiler needs the template’s body (Function templates).

    For a constant the whole project shares, write inline constexpr int min_quality = 20; in a header.

    extern: the older way to share a variable

    Before inline variables, a shared global was declared extern in a header and defined in exactly one source file. extern makes the line a declaration only:

    #include <print>
    
    extern int reads_seen; // declaration: defined somewhere else
    
    int main() {
        ++reads_seen;
        std::println("{}", reads_seen);
    }
    
    int reads_seen = 0; // the one definition

    Output

    1

    You’ll meet extern in older code and C libraries. In new code, prefer an inline variable.

    Internal linkage: helpers private to one file

    A helper that one source file uses shouldn’t be shared with the whole program: if bases.cpp and qualities.cpp each define their own is_valid(char), the link fails with multiple definition. Put the helper in an unnamed namespace, or mark it static, and it gets internal linkage: each file keeps its own, invisible to the others.

    #include <print>
    
    namespace {
    
    bool is_valid_base(char c) {
        return c == 'A' || c == 'C' || c == 'G' || c == 'T';
    }
    
    } // namespace
    
    static bool is_valid_quality(char c) {
        return c >= '!' && c <= 'J';
    }
    
    int main() {
        std::println("{} {}", is_valid_base('N'), is_valid_quality('I'));
    }

    Output

    false true

    Both forms do the same for functions; the unnamed namespace also works for types, so it’s the one to reach for. Don’t use either in a header: every file that includes it would get its own private copy.

    Which one should I use?

    WhatWhenWhyHow
    Declaration in the header, definition in a .cppOrdinary functions: the default.The body compiles once, and changing it rebuilds only that .cpp.int count_gc(std::string_view s); in dna.h
    inline in the headerShort functions, and variables the whole program shares.Allowed in every file; the linker keeps one copy.inline int count_gc(…) { … }, inline constexpr int min_quality = 20;
    Whole definition in the headerTypes, templates, constexpr functions.The compiler needs all of it in each file that uses it.struct Read { … };, template <typename T> T larger(T a, T b) { … }
    Unnamed namespace in the .cppHelpers only one source file uses.Private to that file, so nothing can clash.namespace { bool is_valid(char c) { … } }

    Rule of thumb: headers hold declarations, types, templates and inline code, in your project’s namespace and behind #pragma once. Source files hold the rest, with their helpers in an unnamed namespace.

    Under the hood

    The linker works from each object file’s table of symbols, which you listed with nm in How a C++ program is built. Compile the inline example’s dna.cpp and valid.cpp with -c, and list their symbols:

    g++ -std=c++23 -c dna.cpp -o dna.o && nm -C dna.o
    g++ -std=c++23 -c valid.cpp -o valid.o && nm -C valid.o | grep is_valid
    

    With GCC on Linux, the letter before each name tells the linker what to do with it:

    LetterMeaningFrom this lesson
    TDefined here; must be unique in the program.dna::gc_percent
    WWeak: other files may define it too; the linker keeps one.dna::count_gc (inline), and the std::string_view member functions it calls
    uOne shared object, however many files define it.dna::reads_seen (inline variable)
    tLocal to this file; never matched with other files.(anonymous namespace)::is_valid_base, is_valid_quality
    UUsed here, defined somewhere else.Parts of the standard library that std::println calls

    Multiple definition means two Ts for one name; undefined reference means a U with nothing to match it. The namespace is part of each name, so count_gc and dna::count_gc are different symbols.

    PerformanceWhat a header costs

    Every source file that includes a header compiles all of it again, and every header it includes. Big projects spend much of their build time reading the same headers over and over. Keep headers small, include only what each file uses, and keep bodies in .cpp files unless they must be in the header. Modules tackle this in the language itself.

    Common pitfalls

    Defining a function outside its namespace

    The header declares count_gc inside namespace dna, but dna.cpp defines it at the top level. That’s a different function, count_gc with no namespace, and nothing defines dna::count_gc:

    3 files, built together

    dna.h
    #pragma once
    
    #include <string_view>
    
    namespace dna {
    
    int count_gc(std::string_view sequence);
    
    } // namespace dna
    dna.cpp
    #include "dna.h"
    
    int count_gc(std::string_view sequence) {
        int count = 0;
        for (char base : sequence) {
            count += base == 'G' || base == 'C';
        }
        return count;
    }
    main.cpp
    #include <print>
    
    #include "dna.h"
    
    int main() {
        std::println("{}", dna::count_gc("GATTACA"));
    }

    Build and run

    g++ -std=c++23 -Wall -Wextra -Wpedantic dna.cpp main.cpp -o app
    ./app

    The compiler rejects this

    ld: in function `main':
    main.cpp: undefined reference to `dna::count_gc(std::basic_string_view<char, std::char_traits<char> >)'
    collect2: error: ld returned 1 exit status

    Wrap the definition in namespace dna { … }, or write it by its full name, int dna::count_gc(std::string_view sequence), as dna.cpp did for gc_percent above. With the full name, a mismatch is a compile error in dna.cpp instead of a link error.

    Defining a template in a source file

    Declare a template larger in stats.h, define it in stats.cpp like an ordinary function, call larger(3, 7) from main.cpp, and the link fails with undefined reference to larger<int>. main.cpp sees only the declaration, so it can’t make larger<int> itself; stats.cpp has the body but never uses larger<int>, so it doesn’t make one either. Put the whole template in the header.

    Try it yourself

    Try it yourself

    Put count_gc in a namespace called dna, and make is_gc private to this file with an unnamed namespace. Update the call in main.

    #include <print>
    #include <string_view>
    
    bool is_gc(char base) {
        return base == 'G' || base == 'C';
    }
    
    int count_gc(std::string_view sequence) {
        int count = 0;
        for (char base : sequence) {
            count += is_gc(base);
        }
        return count;
    }
    
    int main() {
        std::println("{}", count_gc("GGCAT"));
    }

    Expected output

    3
    Show a hint

    Wrap count_gc in namespace dna { … } and is_gc in namespace { … }. Then main has to call dna::count_gc.

    Show a solution
    #include <print>
    #include <string_view>
    
    namespace {
    
    bool is_gc(char base) {
        return base == 'G' || base == 'C';
    }
    
    } // namespace
    
    namespace dna {
    
    int count_gc(std::string_view sequence) {
        int count = 0;
        for (char base : sequence) {
            count += is_gc(base);
        }
        return count;
    }
    
    } // namespace dna
    
    int main() {
        std::println("{}", dna::count_gc("GGCAT"));
    }

    namespace dna gives count_gc a surname, so another library's count_gc can't clash with it. The unnamed namespace gives is_gc internal linkage: if you split this file into dna.h and dna.cpp, is_gc stays private to dna.cpp, and another source file can have its own is_gc.

    Saved in this browser only.