6.2 Multi-file Builds and Headers
As programs grow, put declarations in .h header files and implementations in .cpp source files.
cpp
// geometry.h
#ifndef GEOMETRY_H
#define GEOMETRY_H
double circle_area(double radius);
#endifcpp
// geometry.cpp
#include "geometry.h"
#define PI 3.1415926
double circle_area(double radius) {
return PI * radius * radius;
}cpp
// main.cpp
#include <iostream>
#include "geometry.h"
int main() {
std::cout << circle_area(5) << std::endl;
return 0;
}Compile the related source files together:
bash
g++ -Wall geometry.cpp main.cpp -o areaThe #ifndef / #define / #endif lines in a header are called an include guard; they stop the same header from being included twice.
Loading interactive lab...
Loading concept check...
Loading practice...