bhylu.com

Advertisements

C Multiple Source Files

Give a calibration module one guarded header, one implementation file and one caller.

How it works

A translation unit is a source file after preprocessing its includes. Separate modules share declarations through headers and are linked into one program. Put an externally visible function definition in one implementation file, not in every including file. An include guard prevents repeated declarations or type definitions when a header is reached more than once during preprocessing. A header should include what its own declarations require. This module has a small arithmetic contract: its caller supplies values whose sum fits in int.

Run it locally

Use a hosted C17 compiler in a separate lab folder. The command assumes a driver named cc; substitute gcc, clang or zig cc as appropriate. C does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed for these C programs.

cc -std=c17 -Wall -Wextra -Wpedantic -Werror modules.c survey.c -o lesson

On Windows, use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Math-library linking differs by toolchain; GCC on many Unix systems needs -lm after the source.

Download the complete C source. File-writing labs must run in an empty private directory, away from existing reports.

Example

C17 · modules.c

#include <stdio.h>
#include "survey.h"

int main(void) {
    printf("Calibrated: %d\n", survey_adjust(20, -3));
    return 0;
}

Expected result

Calibrated: 17

Save all three displayed files together and compile modules.c and survey.c in one driver command. The header lets the caller type-check the operation before linking. The implementation includes that same header so declaration mismatches are visible. Larger builds can compile object files separately, but incremental builds must rebuild callers when relevant header contracts change.

Supporting file: survey.h

survey.h

#ifndef BHYLU_SURVEY_H
#define BHYLU_SURVEY_H
int survey_adjust(int reading, int offset);
#endif

Download survey.h

Supporting file: survey.c

survey.c

#include "survey.h"
int survey_adjust(int reading, int offset) {
    return reading + offset;
}

Download survey.c

For language and library rules, consult the WG14 C working group and its public C11 committee draft, which describes the core facilities used here; C17 incorporates corrections. Check your compiler and runtime documentation for implementation details.

Advertisements