6.2 Multi-file Builds and Headers
As programs grow, put declarations in .h header files and implementations in .c source files.
c
// geometry.h
#ifndef GEOMETRY_H
#define GEOMETRY_H
double circle_area(double radius);
#endifc
// geometry.c
#include "geometry.h"
#define PI 3.1415926
double circle_area(double radius) {
return PI * radius * radius;
}c
// main.c
#include <stdio.h>
#include "geometry.h"
int main(void) {
printf("%.2f\n", circle_area(5));
return 0;
}Compile the related source files together:
bash
gcc -Wall geometry.c main.c -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...