Skip to content

Checkpoint: Separate Source Files

The Course
•
40 min study

The project's parser, add_session and total are needed by two programs: the report, and a test program with its own main. Copying the functions into both would mean two copies to keep in step. Instead, one .c file holds the helper definitions, each program's main lives in its own .c file, and a header file, ending in .h, carries the declarations that let them call each other.

Predict and run

Predict before running C
#include <stdio.h>

int twice(int n);

int twice(int n) {
    return n * 2;
}

int main(void) {
    printf("%d\n", twice(6));
    return 0;
}
Check your prediction
Text
12

The first twice line, ending in a semicolon, is a declaration: the function's name, parameters and return type. The second, with a body, is the definition. Splitting a program puts the declaration in a header that every file can include, and the definition in exactly one .c file.

How the files connect

Building a multi-file program has two stages.

  1. Compiling. Each .c file is compiled on its own into an object file. #include "report.h" pastes the header's text in first, so each call in main.c is checked against a declaration. The body is not needed yet.
  2. Linking. The linker joins the object files and connects each call to the one definition with that name. If no file defines it, compiling succeeds and linking fails:
Shell
undefined reference to `total_minutes'
collect2: error: ld returned 1 exit status

The wording differs between systems, but the meaning is "declared, called, never defined". Two definitions with the same name are also a link error, which is why the test executable is linked with report.c but not with main.c: each has a main.

The header in the editor below starts with a header guard: #ifndef REPORT_H, #define REPORT_H, and #endif at the end. On the first inclusion REPORT_H is undefined, so the contents are used and the name gets defined; any later inclusion in the same file skips everything, so struct Session is not defined twice. Include your own headers with quotes and standard headers with angle brackets. Never #include a .c file, or its definitions end up in several object files.

Run the shared helper tests

These tabs hold the same report.h and report.c that the final project downloads, with the test program test_report.c as the entry file.

Headers, implementation and tests C
#include "report.h" #include <assert.h> #include <stddef.h> #include <stdio.h> int main(void) { // Calls that change state run in their own statement; assert checks the // saved result, so the work still happens in a build that defines NDEBUG. int ok = 0; int out = 77; const char *bad[] = {"", "0", "181", "-1", " 25", "25x", "\n", "99999999999999999999999999", "25\nextra"}; for (int i = 0; i < 9; i++) { ok = parse_minutes(bad[i], &out); assert(!ok && out == 77); } ok = parse_minutes(NULL, &out); assert(!ok && out == 77); ok = parse_minutes("25", NULL); assert(!ok); ok = parse_minutes("1", &out); assert(ok && out == 1); ok = parse_minutes("180\n", &out); assert(ok && out == 180); ok = parse_minutes("025", &out); assert(ok && out == 25); struct Session sessions[SESSION_CAPACITY] = {0}; int count = 0; assert(total_minutes(sessions, count) == 0); ok = add_session(sessions, &count, 0); assert(!ok && count == 0); ok = add_session(sessions, &count, 181); assert(!ok && count == 0); ok = add_session(NULL, &count, 1); assert(!ok && count == 0); ok = add_session(sessions, NULL, 1); assert(!ok); for (int i = 0; i < SESSION_CAPACITY; i++) { ok = add_session(sessions, &count, 25); assert(ok); } assert(count == SESSION_CAPACITY); ok = add_session(sessions, &count, 30); assert(!ok && count == SESSION_CAPACITY); assert(total_minutes(sessions, count) == 200); (void)ok; // with NDEBUG the asserts vanish; this keeps ok "used" printf("Report checks passed\n"); return 0; } #include "report.h" #include <stddef.h> int parse_minutes(const char *text, int *out) { if (text == NULL || out == NULL || *text == '\0') { return 0; } int value = 0; int i = 0; while (text[i] >= '0' && text[i] <= '9') { int digit = text[i] - '0'; /* Reject before multiplication: even a very long number cannot overflow. */ if (value > (MAX_MINUTES - digit) / 10) { return 0; } value = value * 10 + digit; i++; } if (i == 0 || value < 1) { return 0; } if (text[i] == '\n') { i++; } if (text[i] != '\0') { return 0; } *out = value; return 1; } int add_session(struct Session sessions[], int *count, int minutes) { if (sessions == NULL || count == NULL || *count < 0 || *count >= SESSION_CAPACITY || minutes < 1 || minutes > MAX_MINUTES) { return 0; } sessions[*count].minutes = minutes; (*count)++; return 1; } int total_minutes(const struct Session sessions[], int count) { int total = 0; for (int i = 0; i < count; i++) { total += sessions[i].minutes; } return total; } #ifndef REPORT_H #define REPORT_H #define SESSION_CAPACITY 8 #define MAX_MINUTES 180 struct Session { int minutes; }; /* On failure, leave *out unchanged. */ int parse_minutes(const char *text, int *out); /* Caller supplies count initialized records, 0 <= count <= SESSION_CAPACITY. */ int total_minutes(const struct Session sessions[], int count); /* Returns 0 without changing storage when invalid or full. */ int add_session(struct Session sessions[], int *count, int minutes); #endif
Check your prediction
Text
Report checks passed

Open each tab before you go on. report.h holds the guard, struct Session and one commented prototype per helper; report.c includes it and defines each helper once; test_report.c includes it too and has its own main.

What you will use

  • Declarations as contracts. Each prototype in report.h has a comment stating its precondition or its failure behavior. Read them as promises.
  • Definitions in one place. report.c implements every declared function and includes its own header, so the compiler checks that the two agree.
  • Two entry files. main.c and test_report.c each have a main, and each is linked with report.c, never with each other.

Plan before you type

  1. Read report.h above and write down what each function promises on failure.
  2. Run the helper tests and confirm the success line.
  3. For the practice task, write minutes.h first: the guard, then one commented declaration per function.
  4. Write the assertions in main.c, run, and read the link error: it lists exactly the functions minutes.c still has to define.
  5. Write the definitions in minutes.c until the assertions pass.
Prove it can fail

In the multi-file editor above, rename total_minutes to total_minute in report.c only and run. Compiling still succeeds for test_report.c, but linking fails with an undefined reference, because the header promised a function that no file defines. Restore it. Then change MAX_MINUTES in report.h to 179: the assertion that accepts "180\n" fails, which shows the header's value reaches both files. Reset when you are done.

Mistakes worth checking for

  • call to undeclared function. The file calls a function without including the header that declares it, or the declaration comes after the call.
  • undefined reference or Undefined symbols. The declaration exists but no linked file defines it: a misspelled name, or report.c left out of the build command.
  • duplicate symbol or multiple definition of main. Two entry files were linked together, or a .c file was included in another.
  • redefinition of 'struct Session'. A header without a guard was included twice in one file.

Practice

Exercise

Your turn

Split two helpers across three files, the way report.h, report.c and test_report.c are split. In the tabs below:

  • minutes.h: a header guard (MINUTES_H) and the declarations int valid_minutes(int minutes); and int accepted_total(const int values[], int count);, each with a one-line comment stating its contract.
  • minutes.c: includes "minutes.h" and defines both functions. valid_minutes accepts 1 through 180; accepted_total sums only the valid durations, using valid_minutes.
  • main.c: for {25, 0, 181, 10}, assert the total is 35, that count 0 gives 0 and count 1 gives 25, then print:
Shell
Total: 35
Accepted total checks passed
Your workspace C
#include <assert.h> #include <stdio.h> #include "minutes.h" int main(void) { // Write the array, the three assertions and the two printf lines here. printf("Not written yet\n"); return 0; } /* minutes.h: write the header guard and the two declarations here. */ #include "minutes.h" /* Write the two definitions here. */
Hint 1: the idea

The header is the only file the other two share. main.c needs just the declarations to compile its calls, and the linker then finds the one definition of each function in minutes.c. The guard is three lines around everything else in the header.

Hint 2: a first step

Fill in minutes.h only, then write one assertion in main.c and run. Compiling now succeeds, and linking fails with an undefined reference (or Undefined symbols) naming accepted_total: the header promised a function that no file defines yet. That message is your to-do list for minutes.c.

Show one solution
One solution in three files C
#include <assert.h> #include <stdio.h> #include "minutes.h" int main(void) { int values[4] = {25, 0, 181, 10}; assert(accepted_total(values, 4) == 35); assert(accepted_total(values, 0) == 0); assert(accepted_total(values, 1) == 25); printf("Total: %d\n", accepted_total(values, 4)); printf("Accepted total checks passed\n"); return 0; } #ifndef MINUTES_H #define MINUTES_H /* Returns 1 for a duration in 1 through 180, otherwise 0. */ int valid_minutes(int minutes); /* Sums the valid durations among the first count values. Requires count >= 0 and values to hold at least count ints. */ int accepted_total(const int values[], int count); #endif #include "minutes.h" int valid_minutes(int minutes) { return minutes >= 1 && minutes <= 180; } int accepted_total(const int values[], int count) { int total = 0; for (int i = 0; i < count; i++) { if (valid_minutes(values[i])) { total += values[i]; } } return total; }
Shell
Total: 35
Accepted total checks passed

main.c compiles because minutes.h declares both functions, and the program links because minutes.c defines each exactly once. minutes.c includes its own header, so if a definition ever drifted from its declaration (say long accepted_total(...)), the compiler would report the conflict instead of the program silently misbehaving. These prototypes could be repeated harmlessly even without the guard, but a header that defines a type, as report.h defines struct Session, cannot, so every header gets one. The values 0 and 181 sit inside the data, so a range one too wide would change the total. Tomorrow you assemble the whole report from these files.

Was this article helpful?

Your response is saved on this device.