C — Organizing code across files
In C, put a function declaration in a header and its definition in one source file. The linker connects the call in another source file to that definition.
A simple example
Use a declaration from a header
- Start with "abc"
- Do this Include string.h, call strlen
- Result 3
#include <stdio.h>
#include <string.h>
int main(void) {
printf("%zu\n", strlen("abc"));
}
3
Share a function between source files
The header declares the interface and the source file supplies its single definition. Include the header in both compilation units so the compiler checks that they agree. The linker combines them.
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
C17. Run these commands from the directory containing the example. Use a Unix-style shell.
cc -std=c17 lesson.c boxes.c -o lesson
./lesson
#ifndef BOXES_H
#define BOXES_H
int remaining(int capacity, int used);
#endif
#include "boxes.h"
int remaining(int capacity, int used) {
return capacity - used;
}
#include <stdio.h>
#include "boxes.h"
int main(void) {
printf("%d\n", remaining(8, 3));
return 0;
}
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.