Lesson contents

C++ — Organizing code across files

In C++, a header can declare a function in a namespace while a separate source file defines it. Compile and link both source files to call that function from main.

A simple example

Use a standard header

  1. Start with 6 and 4
  2. Do this Include numeric and call gcd
  3. Result 2
The numeric header declares the greatest common divisor function. Two divides both inputs.
lesson.cpp
#include <iostream>
#include <numeric>

int main() {
    std::cout << std::gcd(6, 4) << '\n';
}
Output
2
Advertisements

Share a function between source files

A header declares the function in namespace boxes. A separate translation unit defines it. The qualified name boxes::remaining makes the intended interface explicit.

Room capacity: 8 seats. Already booked: 3 seats. Helper returns: 5 free seats.
Share a room-capacity calculation

A club ticket desk has eight seats and three bookings. Keep the calculation in a helper file so both the booking screen and the check-in screen can use it. With the same inputs, each reports five places left.

Run the example

C++17. Run these commands from the directory containing the example. Use a Unix-style shell.

c++ -std=c++17 lesson.cpp boxes.cpp -o lesson
./lesson
boxes.hpp
#ifndef BOXES_HPP
#define BOXES_HPP
namespace boxes {
    int remaining(int capacity, int used);
}
#endif
boxes.cpp
#include "boxes.hpp"

int boxes::remaining(int capacity, int used) {
    return capacity - used;
}
lesson.cpp
#include <iostream>
#include "boxes.hpp"

int main() {
    std::cout << boxes::remaining(8, 3) << '\n';
}
Output
5

Create the files with the names shown and run the command from their common project folder. The entry point gives the helper a capacity of 8 and a used count of 3. The helper returns 5.

Try it yourself

Change the used count from 3 to 8 in the caller.

Check your answer

Running the same command prints 0. No change to the helper is needed.

C++ language and library reference

Related tags

  • C++
  • modules
  • source files
  • imports