Lesson contents

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

  1. Start with "abc"
  2. Do this Include string.h, call strlen
  3. Result 3
The header supplies the declaration of strlen. The three letters before the terminating zero are counted.
lesson.c
#include <stdio.h>
#include <string.h>

int main(void) {
    printf("%zu\n", strlen("abc"));
}
Output
3
Advertisements

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.

Room capacity: 8 seats. Already booked: 3 seats. Helper returns: 5 free seats.
Share a room-capacity calculation

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
boxes.h
#ifndef BOXES_H
#define BOXES_H
int remaining(int capacity, int used);
#endif
boxes.c
#include "boxes.h"

int remaining(int capacity, int used) {
    return capacity - used;
}
lesson.c
#include <stdio.h>
#include "boxes.h"

int main(void) {
    printf("%d\n", remaining(8, 3));
    return 0;
}
Output
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.

GNU C Language Manual

Related tags

  • C
  • modules
  • source files
  • imports