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
- Start with 6 and 4
- Do this Include numeric and call gcd
- Result 2
#include <iostream>
#include <numeric>
int main() {
std::cout << std::gcd(6, 4) << '\n';
}
2
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.
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
#ifndef BOXES_HPP
#define BOXES_HPP
namespace boxes {
int remaining(int capacity, int used);
}
#endif
#include "boxes.hpp"
int boxes::remaining(int capacity, int used) {
return capacity - used;
}
#include <iostream>
#include "boxes.hpp"
int main() {
std::cout << boxes::remaining(8, 3) << '\n';
}
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.