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.c — provides function definitions
main.c — 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.c
#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.c
#include <stdio.h>
#include "math_utils.h"
int main(void) {
double radius = 3.0;
printf("%.2f\n", circle_area(radius));
printf("%d\n", clamp(125, 0, 100));
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.
gcc -Wall -c math_utils.c -o math_utils.o
gcc -Wall -c main.c -o main.o
gcc main.o math_utils.o -o calculator
# Or compile and link in one command:
gcc -Wall main.c math_utils.c -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.c.
- Create an array and print its minimum and maximum in main.c.
- Compile and link every source file with one gcc command.