Skip to content
Tutorials Center
My learning

Topics

Lesson 50 of 171 ยท Functions

Header Files and Multiple Source Files

Split C++ programs into .h and .cpp files - what goes in a header, include guards and #pragma once, the one-definition rule, how the linker joins files, and modules.

Every example so far fits in one file. Real programs don't. A game engine, a browser or a trading system has thousands of source files, and even a small tool quickly grows past the point where one main.cpp is pleasant to work in. C++ lets you split a program across many source files that are compiled separately and then linked together into one executable. Header files are the glue: they hold the declarations that let one file use what another file defines.

This system is older than C++ itself (it comes from C), and it has rules that surprise newcomers: why does a missing function produce an error from the linker rather than the compiler? Why does including a header twice break the build? Why do some functions live in headers and others don't? In this lesson you'll learn how to split code into .h and .cpp files, what belongs in each, include guards and #pragma once, the one-definition rule, the most common build errors and how to read them, and how C++20 modules aim to replace the whole mechanism. Since our editor compiles a single file, multi-file projects are shown as read-only code, with runnable single-file demos of each idea.

Declarations and definitions, revisited

Recall from Functions the difference between a declaration, which introduces a name and its type, and a definition, which provides the actual body or storage:

C++
int area(int width, int height);          // declaration: "this function exists somewhere"

int area(int width, int height) {         // definition: here's the code
    return width * height;
}

To call a function, the compiler only needs its declaration: it must know the parameter and return types to check the call and generate the code. The definition can be anywhere, even in another file. That's the key idea behind multiple source files:

C++ Calling a function that's defined later

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.

When main is compiled, the compiler has only seen the declarations. It emits calls to "a function named circle_area(double)" and leaves the address blank. The linker fills it in later, once it has found the definition.

Splitting a program into files

Here's a small program split the way most C++ projects are organized: a header with the interface, a source file with the implementation, and a main.cpp that uses it.

C++
// temperature.h: the interface (what other files may use)
#pragma once

#include <string>

namespace weather {
    struct Reading {
        std::string city;
        double celsius;
    };

    double to_fahrenheit(double celsius);
    std::string describe(const Reading& reading);
}
C++
// temperature.cpp: the implementation
#include "temperature.h"   // always include your own header first

#include <format>

namespace weather {
    namespace {
        // Private helper: internal linkage, invisible to other files.
        const char* feel(double celsius) {
            if (celsius < 5) { return "cold"; }
            if (celsius < 22) { return "mild"; }
            return "warm";
        }
    }

    double to_fahrenheit(double celsius) {
        return celsius * 9.0 / 5.0 + 32.0;
    }

    std::string describe(const Reading& reading) {
        return std::format("{}: {:.1f} C / {:.1f} F ({})", reading.city, reading.celsius,
                           to_fahrenheit(reading.celsius), feel(reading.celsius));
    }
}
C++
// main.cpp: uses the interface without knowing how it works
#include <print>
#include "temperature.h"

int main() {
    weather::Reading oslo{"Oslo", -3.5};
    std::println("{}", weather::describe(oslo));
}

Build all source files into one program:

Terminal
g++ -std=c++23 -Wall -Wextra main.cpp temperature.cpp -o weather
./weather

Notice what's not in that command: temperature.h. Headers are never compiled on their own. The preprocessor pastes them into each .cpp file that includes them. Each .cpp file plus everything it includes is a translation unit, and the compiler processes each translation unit independently, producing an object file (main.o, temperature.o). The linker then combines the object files and resolves every call to its definition. How C++ Works walks through these stages.

Include style follows a convention: #include "file.h" with quotes for your project's headers (searched next to the current file first), and #include <header> with angle brackets for the standard library and installed libraries. Larger projects pass include directories to the compiler with -I, which you'll set up in Build Systems: Make and CMake.

What goes in a header and what doesn't

Usually in a header (.h, .hpp) Usually in a source file (.cpp)
Function declarations Function definitions (bodies)
Class and struct definitions Member function definitions defined outside the class
inline functions and inline variables Global variable definitions (int counter = 0;)
Templates (full definitions) Private helpers (in an anonymous namespace)
constexpr constants and functions using namespace directives, if you must use them
Type aliases, enums Anything other files don't need to see

Templates and inline functions are in the left column because the compiler needs their full definitions in every translation unit that uses them (see inline Functions and Function Templates). Default arguments belong on the declarations in the header (see Default Arguments).

Two habits keep headers healthy:

  • Make every header self-sufficient. A header should #include everything it uses, so it compiles no matter what was included before it. Including your own header first in its .cpp file checks this automatically.
  • Include what you use, and no more. Every extra include in a header is pasted into every file that includes it, slowing builds. If a header only mentions a type by pointer or reference, a forward declaration like class Database; is often enough.

Include guards and #pragma once

Headers include other headers, so the same header often gets pasted into one translation unit more than once. Suppose main.cpp includes both order.h and customer.h, and both of those include money.h. Without protection, struct Money is defined twice in main.cpp, and the compiler stops with "redefinition of 'struct Money'".

The traditional fix is an include guard, a preprocessor check around the whole header:

C++
// money.h
#ifndef SHOP_MONEY_H
#define SHOP_MONEY_H

struct Money {
    long long cents;
};

#endif // SHOP_MONEY_H

The first inclusion defines SHOP_MONEY_H and keeps the content. Any later inclusion in the same translation unit sees that the macro already exists and skips everything up to #endif. You can watch it work by pasting a "header" twice into one file:

C++ An include guard at work

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.

Delete the second #ifndef SHOP_MONEY_H line and its #endif, and the build fails with "redefinition of 'struct Money'". The guard macro must be unique across the whole project; a pattern like PROJECT_PATH_FILE_H avoids clashes. Never start it with an underscore followed by a capital letter (_MONEY_H), since those names are reserved (see Keywords and Identifiers).

The modern alternative is one line at the top of the header:

C++
#pragma once

#pragma once isn't part of the C++ standard, but GCC, Clang, MSVC and every other mainstream compiler support it. It's shorter, can't suffer from copy-pasted guard names, and is what most new code uses. Its only weakness is unusual build setups where the same file is reachable through different paths (such as symbolic links or network drives). Either approach is fine; pick one per project and use it in every header.

Include guards protect against duplicates within one translation unit. They do nothing across different .cpp files, since each translation unit is compiled from scratch. That's why a non-inline function defined in a header still breaks the build when two .cpp files include it, as the next section explains.

The one-definition rule (ODR)

The one-definition rule has two parts that matter in practice:

  1. Within one translation unit, each class, function, variable and template may be defined only once. Include guards enforce this for headers.
  2. Across the whole program, each non-inline function and variable must be defined exactly once. Classes, templates, and inline functions and variables may be defined in several translation units, as long as all the definitions are identical.

Breaking part 2 produces the two most common linker errors:

Multiple definition: the same function or variable is defined in two object files, typically because a non-inline function or a global variable was defined in a header:

TEXT
/usr/bin/ld: temperature.o: in function `weather::to_fahrenheit(double)':
temperature.cpp:(.text+0x0): multiple definition of `weather::to_fahrenheit(double)'; main.o:main.cpp:(.text+0x0): first defined here
collect2: error: ld returned 1 exit status

Fixes: move the definition into a .cpp file and keep only a declaration in the header, or mark the definition inline. For globals, use inline variables (C++17) or extern declarations.

Undefined reference: a function was declared and called but never defined, or its .cpp file wasn't part of the build. This example fails on purpose so you can see the error:

C++ An undefined reference (fails on purpose)

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.

The compiler is perfectly happy, since the declaration is all it needs. The linker then fails with "undefined reference to exchange_rate(char const*, char const*)" because it can't find the definition anywhere. In real projects the usual causes are:

  • forgetting to add the .cpp file to the build command or CMakeLists.txt;
  • a signature mismatch: the header says double f(int) but the source defines double f(long), which is a different overload;
  • defining the function in a different namespace than the one declared (area instead of geometry::area);
  • a missing library on the link line, such as a third-party library's -l flag.

The error mentions the mangled name, demangled into the readable signature. When you see a name you didn't expect, compare it character by character with your definition.

Global variables across files

A global variable defined in a header would break the ODR as soon as two files included it. The classic C-compatible solution splits it into a declaration with extern in the header and one definition in a .cpp file. Since C++17, an inline variable in the header does the same job in one line:

C++
// settings.h
#pragma once

extern int log_level;            // classic: declaration only...
inline int max_retries = 3;      // C++17: defined here, one shared object everywhere
C++
// settings.cpp
#include "settings.h"

int log_level = 2;               // ...and the single definition lives here

Constants are simpler: constexpr int max_users = 64; in a header is fine without inline, because namespace-scope const and constexpr variables have internal linkage, so each file gets its own private copy and no ODR conflict arises. (Use inline constexpr for large constant tables to share one copy.)

The cost of headers

Headers work, but they have real costs that you'll feel in large projects:

  • Slow builds. #include <vector> pastes tens of thousands of lines into every file that includes it, and every one of those files compiles them again. A project with 1,000 .cpp files parses the standard library headers 1,000 times.
  • Leaky isolation. Macros defined in one header affect every header included after it, so header order can change meaning.
  • Implementation details exposed. A class's private members must appear in its header, so changing a private member forces every user to recompile. (The pimpl idiom works around this; see Nested and Local Classes.)

You can watch the "leaky" part directly. An include is pure text pasting, so macros a header defines are visible to every line after it, and what a file sees depends on what it included before that line:

C++ Includes change what follows

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.

__cpp_lib_ranges and __cpp_lib_print are feature-test macros: library headers define them, and their values are dates (year and month) of the feature's version. Portable code tests them with #ifdef to check whether a feature is available, and the <version> header defines all of them at once. Here the macro doesn't exist above #include <ranges> and does exist below it. Ordinary macros in your own headers behave exactly the same way, which is why header order can matter. __cplusplus identifies the language standard the compiler is using.

Modules: the future (C++20)

C++20 introduced modules, a replacement for headers that fixes their biggest problems. A module is compiled once into a binary interface that importers load quickly; macros don't leak in or out; and only names marked export are visible to importers:

C++
// temperature.cppm: a module interface unit
export module weather;

import std;   // C++23: the whole standard library in one fast import

export namespace weather {
    double to_fahrenheit(double celsius) {
        return celsius * 9.0 / 5.0 + 32.0;
    }
}

// Not exported: invisible to importers, no anonymous namespace needed.
double internal_helper(double x) { return x * 2; }
C++
// main.cpp
import weather;
import std;

int main() {
    std::println("{}", weather::to_fahrenheit(21.0));
}

Modules are real and production-ready in recent MSVC, Clang and GCC versions, but tooling is still catching up: build systems must compile modules in dependency order, and support in CMake, IDEs and package managers has only recently matured. import std; isn't available in our online editor, which is why every example on this site uses #include. For now, you'll meet headers in nearly every existing codebase, so you need to know them well. The C++20 Modules lesson covers modules in depth.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A function is declared in a header and called from main.cpp, but its .cpp file was left out of the build. Which tool reports the error?

    The compiler only needs the declaration to compile the call. The linker then can't find the definition in any object file and reports an undefined reference.
  2. 2. What problem do include guards (or #pragma once) solve?

    Guards stop a second inclusion within the same translation unit. Each .cpp file is compiled separately, so guards can't prevent multiple-definition link errors across files.
  3. 3. A header contains int counter = 0; and is included by a.cpp and b.cpp. What happens?

    Each translation unit defines the same global, which violates the one-definition rule. Use extern in the header plus one definition in a .cpp, or an inline variable (C++17).
  4. 4. Which of these normally belongs in a header file?

    Class definitions and templates must be visible in every translation unit that uses them, and the ODR allows them to be defined in several files. Non-inline bodies and globals go in .cpp files.

Summary

  • A program can be split into many source files; each .cpp plus its includes is a translation unit, compiled separately and joined by the linker.
  • Headers hold declarations and the definitions that must be visible everywhere (classes, templates, inline and constexpr things). Function bodies and global variables go in .cpp files.
  • Use #include "..." for your own headers and <...> for libraries. Keep headers self-sufficient and include only what you use.
  • Include guards or #pragma once prevent duplicate definitions within one translation unit; use one of them in every header.
  • The one-definition rule: non-inline functions and variables are defined exactly once in the program. Violations show up as multiple definition or undefined reference linker errors.
  • Share globals with extern plus one definition, or with C++17 inline variables.
  • C++20 modules (export module, import) are the future replacement for headers, with faster builds and real isolation; tooling support is still maturing.

Next: The Preprocessor and Macros.