Larger programs usually place public interfaces in a header, implementations in a source file, and calls in a main file. Each source file is compiled independently into an object file, then the linker combines those objects into an executable.
math_utils.h — declares the shared interface
math_utils.cpp — provides function definitions
main.cpp — calls the public functions
Headers and include guards
A header guard uses a unique uppercase name. The first inclusion defines that name; later inclusions see a false ifndef condition and skip the body. Headers should contain declarations, not ordinary function definitions that would create multiple copies.
math_utils.h
#ifndef MATH_UTILS_H
#define MATH_UTILS_H
double circle_area(double radius);
int clamp(int value, int minimum, int maximum);
#endifKNOWLEDGE QUIZ
Implementation and main files
math_utils.cpp
#include "math_utils.h"
#define PI 3.1415926
double circle_area(double radius) {
return PI * radius * radius;
}
int clamp(int value, int minimum, int maximum) {
if (value < minimum) {
return minimum;
}
if (value > maximum) {
return maximum;
}
return value;
}main.cpp
#include <iomanip>
#include <iostream>
#include "math_utils.h"
int main() {
double radius = 3.0;
std::cout << std::fixed << std::setprecision(2);
std::cout << circle_area(radius) << '\n';
std::cout << clamp(125, 0, 100) << '\n';
return 0;
}KNOWLEDGE QUIZ
Compile separately, then link
The -c option compiles without linking and produces .o object files. The final command links those objects into calculator. After changing only main, you can recompile main and link again.
g++ -Wall -c math_utils.cpp -o math_utils.o
g++ -Wall -c main.cpp -o main.o
g++ main.o math_utils.o -o calculator
# Or compile and link in one command:
g++ -Wall main.cpp math_utils.cpp -o calculatorSplit an array statistics program
Split an array statistics program into three files.
- Declare min_value and max_value in stats.h with a STATS_H guard.
- Implement both functions in stats.cpp.
- Create an array and print its minimum and maximum in main.cpp.
- Compile and link every source file with one g++ command.