Several files: headers, source files and linking#

Every program so far is one file. The engine’s src/ folder holds 43 C++ files: mostly one header and one source file per class, plus the command-line tool and the Python bindings. This chapter splits the LJPotential of Classes into a header, a source file and a main, compiles them separately and links them. It pays off two promises: A first program showed that #include <cmath> pastes in the declaration of pow, and Functions promised declarations of your own.

Three files#

The header lj.h declares the class: its members and the functions it has, without their code.

Listing 24 lj.h#
 1#ifndef LJ_H
 2#define LJ_H
 3
 4// An LJ energy function: declarations only. The code is in lj.cpp.
 5class LJPotential {
 6public:
 7    LJPotential(double epsilon, double sigma, double cutoff);
 8    double energy(double r) const;
 9
10private:
11    double epsilon_;
12    double sigma_;
13    double cutoff_;
14};
15
16#endif

The source file lj.cpp holds the code, the definitions. It includes its own header, then writes each function out in full. LJPotential::energy means “the function energy of the class LJPotential”; :: joins the class name and the member name, as in std::pow.

Listing 25 lj.cpp#
 1#include "lj.h"
 2
 3#include <cmath>
 4
 5LJPotential::LJPotential(double epsilon, double sigma, double cutoff) {
 6    epsilon_ = epsilon;
 7    sigma_ = sigma;
 8    cutoff_ = cutoff;
 9}
10
11double LJPotential::energy(double r) const {
12    if (r > cutoff_) {
13        return 0.0;
14    }
15    double sr6 = std::pow(sigma_ / r, 6);
16    return 4.0 * epsilon_ * (sr6 * sr6 - sr6);
17}

main.cpp includes the header and uses the class. It never sees the formula:

Listing 26 main.cpp#
1#include <iostream>
2
3#include "lj.h"
4
5int main() {
6    LJPotential argon(1.0, 1.0, 2.5);
7    std::cout << "U(1.5) = " << argon.energy(1.5) << "\n";
8    return 0;
9}

#include "lj.h" uses quotes, not angle brackets. Quotes tell the compiler to look first in the folder of the file being compiled; angle brackets, as in <cmath>, look in the folders where the compiler keeps the standard library’s headers (and in any folder added with the -I option).

Include guards#

Lines 1, 2 and 16 of lj.h are an include guard. A header is often included more than once into the same source file, usually indirectly. In the engine, for example, lj_potential.h includes both force_calculator.h and geometry.h, and force_calculator.h includes geometry.h again. Without a guard, the class would be pasted, and so defined, twice. This copy of lj.h has its guard lines removed, and main.cpp includes it twice:

$ clang++ -std=c++17 -c main.cpp -o main.o
In file included from main.cpp:4:
./lj.h:3:7: error: redefinition of 'LJPotential'
    3 | class LJPotential {
      |       ^
main.cpp:3:10: note: './lj.h' included multiple times, additional include site here
    3 | #include "lj.h"
      |          ^
main.cpp:4:10: note: './lj.h' included multiple times, additional include site here
    4 | #include "lj.h"
      |          ^
./lj.h:3:7: note: unguarded header; consider using #ifdef guards or #pragma once

The guard works in the preprocessing stage, before any compiling. #ifndef LJ_H means “only if the name LJ_H is not yet defined, keep the lines up to #endif”; #define LJ_H then defines it. The first inclusion keeps the class and defines LJ_H; every later inclusion finds LJ_H defined and drops the whole header. #pragma once at the top of a header does the same in one line; it is not part of the C++ standard, but every major compiler supports it, as clang’s note suggests. The engine uses guards: lj_potential.h starts with #ifndef LJ_POTENTIAL_H, geometry.h with #ifndef GEOMETRY_H.

How the engine builds: CMake#

Typing one command per file does not scale to dozens of files. The engine lists its files in CMakeLists.txt at the repository root, and CMake turns that list into the compile and link commands. Three of its entries:

add_library(EngineLib STATIC
    src/engine/force_calculator.cpp
    src/engine/molecular_dynamics.cpp
    src/engine/md_state.cpp
    src/engine/integrators/integrator.cpp
    src/engine/integrators/velocity_verlet_integrator.cpp
    src/engine/integrators/leapfrog_integrator.cpp
    src/engine/thermostats/thermostat.cpp
    src/engine/thermostats/velocity_rescale_thermostat.cpp
    src/engine/thermostats/langevin_thermostat.cpp
    src/engine/potentials/lj_potential.cpp
    src/engine/potentials/lj_kernels.cpp
    src/engine/potentials/dft_potential.cpp
)
target_link_libraries(EngineLib PUBLIC BuilderLib)

add_executable(run_simulation
    src/tools/run_simulation.cpp
)
target_link_libraries(run_simulation PRIVATE BuilderLib EngineLib)
  • add_library(EngineLib STATIC ...) compiles each listed source file into an object file and packs them into one static library, the file libEngineLib.a: a bundle of object files, ready to link. Listing its contents shows one object file per source file:

    $ ar t build/libEngineLib.a
    __.SYMDEF
    force_calculator.cpp.o
    molecular_dynamics.cpp.o
    md_state.cpp.o
    integrator.cpp.o
    velocity_verlet_integrator.cpp.o
    leapfrog_integrator.cpp.o
    thermostat.cpp.o
    velocity_rescale_thermostat.cpp.o
    langevin_thermostat.cpp.o
    lj_potential.cpp.o
    lj_kernels.cpp.o
    dft_potential.cpp.o
    

    (__.SYMDEF is an index of the names the library has, for the linker.)

  • add_executable(run_simulation ...) compiles the command-line tool’s one source file, which holds its main.

  • target_link_libraries gives the linker the libraries to match against: run_simulation’s needs are met by BuilderLib (geometry, builders, file readers) and EngineLib (the force calculator, the potentials, the MD loop).

A source file missing from add_library produces exactly the link error above, naming the functions it should have provided. Headers are not listed: they reach the compiler through #include.

Check yourself#

1. You change the formula in lj.cpp. Which commands must run again before ./pair shows the change?

clang++ -std=c++17 -c lj.cpp -o lj.o and the link, clang++ lj.o main.o -o pair. main.o does not change: main.cpp and lj.h are untouched.

2. main.cpp compiles without error but the link fails with “Undefined symbols … LJPotential::energy”. What is missing?

The definition of energy: the object file that has it, lj.o, was not given to the linker, or lj.cpp does not define it. The declaration in lj.h was enough to compile main.cpp, so the compiler could not notice.

3. Why does the engine’s geometry.h need an include guard even though no file writes #include “geometry.h” twice?

Because it arrives twice indirectly: lj_potential.h includes force_calculator.h, which includes geometry.h, and then includes geometry.h itself. Without the guard, Geometry would be defined twice in the same source file.

Next#

This is the last chapter of the C++ module. The language you have now (functions, vectors, classes, the plug, headers and linking) is the language the engine is written in.

Every program in this module was linked into an executable with its own main, started from the terminal. The home page starts the engine differently: a Python script imports it and calls it. The pybind11 module builds that bridge, first for the lj_energy function of Functions, then for the engine’s classes.