Modular programs: contracts and builds
Design a small score module with a clear invariant, private validation, failure behavior, and correct rebuild dependencies.
In this chapter8 sections
A growing program becomes easier to understand when each part has a clear responsibility. Modules can hide details and share a small interface. We will connect that design to declarations, private helpers, and rebuild dependencies.
1. Start with a responsibility and an invariant
An invariant is a condition the design intends to preserve at defined boundaries. Here a score is an integer from zero through one hundred. The module accepts a candidate value, checks it, and changes the existing score only on success. It has no allocation ownership to transfer. A more complex module would also specify resource lifetime, borrowing, and cleanup.
- Input
- A candidate integer and a score pointer
- Success
- Store a valid score; return true
- Failure
- Return false; preserve prior state
2. Make the public interface small
#ifndef CODEDILE_SCORE_H
#define CODEDILE_SCORE_H
#include <stdbool.h>
struct CodedileScore { int points; };
/* Accept 0..100. On failure, leave a non-null score unchanged. */
bool codedile_score_set(struct CodedileScore *score, int points);
#endif
The header exposes the structure so callers can create it directly. That makes the representation part of the interface: callers can also write an invalid member value themselves. This design therefore relies on a documented caller discipline; it does not enforce the invariant against every possible write. An opaque type, introduced in the earlier data-interface lesson, can hide the representation when stronger control is needed.
3. Keep implementation choices behind that interface
#include "score.h"
#include <stddef.h>
static bool valid_points(int points)
{
return points >= 0 && points <= 100;
}
bool codedile_score_set(struct CodedileScore *score, int points)
{
if (score == NULL || !valid_points(points)) return false;
score->points = points;
return true;
}
The private helper expresses the accepted range in one place. Its static function identifier has internal linkage. The public function validates before writing, so a rejected request leaves the previous state unchanged. Do not write first and hope to recover the previous value later. Including the public header also makes a conflicting implementation signature visible to the compiler.
4. Test the boundary, including rejection
#include "score.h"
#include <assert.h>
#include <stddef.h>
int main(void)
{
struct CodedileScore score = { .points = 0 };
bool accepted = codedile_score_set(&score, 73);
assert(accepted && score.points == 73);
bool rejected = codedile_score_set(&score, 101);
assert(!rejected && score.points == 73);
bool null_rejected = codedile_score_set(NULL, 10);
assert(!null_rejected);
return 0;
}
The client checks an accepted value, an out-of-range value, and a null request. These checks target the public behavior rather than the helper’s implementation. The object starts in a valid state. An arbitrary non-null pointer is not validated merely by checking it against NULL; the caller still guarantees its type, lifetime, alignment, and writability.
This module has no synchronization and makes no promise that concurrent access to one score is safe. Adding files or static helpers does not add thread safety. If the project later needs shared concurrent state, the interface and implementation must define the synchronization contract explicitly.
5. A build records dependencies, not just filenames
For this small project, the GCC driver can compile both source files and link them in one invocation. Run these example commands from their folder in a suitable Unix-like shell. A successful run produces no output; assertions report a failed expectation in an assertions-enabled build.
gcc -std=c17 -Wall -Wextra main.c score.c -o score_demo
./score_demo
| Change | Typical rebuild consequence |
|---|---|
| Only score.c implementation changes | Recompile score.c and relink the executable; unchanged clients can often reuse their object files. |
| score.h interface changes | Recompile source files that depend on the changed header, including the implementation and clients, then relink. |
| Compiler options, target, or generated configuration changes | Affected object files may need rebuilding even if their source text did not change. |
Build tools such as make track targets and prerequisites. Compiler-generated dependency information can include indirect headers, reducing stale-build mistakes. A clean rebuild is useful when checking the dependency setup, but repeatedly rebuilding everything is not a substitute for correct dependency records. Keep generated files, compile options, and required libraries in the reproducible build description.
Primary references and further reading
- WG14 N1570 — public C11 committee draft: 6.2.2, 6.2.7, 6.9. Stable core rules used for the C17 baseline; not the final ISO publication.
- GNU make: rules and prerequisites
- GCC: dependency generation options
Before you move on
- A module should have a coherent responsibility and a clear interface.
- Private representation and helpers can reduce the state other code must understand.
- Build dependencies must account for shared interface changes, as well as implementation files.
Keep these ideas separate
- Private representation / Unrestricted safety
- Hiding data helps control valid operations, but the implementation still needs to preserve its invariant and handle failure.
How would you describe a module’s accepted inputs and unchanged-on-rejection policy to another programmer?
Optional: say it aloud or keep a note. You can continue whenever you are ready.Check your understanding
Optional. Answers are not saved or sent, and reading stays unrestricted.
Read the explanation for every choice
- Including the interface header automatically supplies every definition.
Declarations in a header do not automatically link function bodies.
- The caller should guess the function’s type.
A consistent declaration is needed for checking the interface.
- Share declarations through a header and include the implementation source in the build.
✓ Correct reasoning. The build must translate and connect the definitions the program requires.
C17
Quick reference from the earlier edition
Retained for existing section links and saved passages. The expanded explanation is above; documented corrections are recorded in the source review.
Real C programs are rarely a single file. The conventional pattern splits each logical module into a header (.h, declarations) and a source file (.c, definitions), letting other files #include the header to use the module without needing its function bodies in each caller. Interface and dependency changes can still require rebuilding affected source files. The compiler translates each .c file into an object file (.o) independently; the linker then combines all object files, plus any needed libraries, into the final executable, resolving each function or variable reference to its actual definition.
Rather than typing these compilation commands by hand, most nontrivial projects use a build tool — traditionally make, driven by a Makefile that specifies which files depend on which — so that targets whose prerequisites changed are rebuilt; an unchanged source file can need recompilation after a header changes. Reusable code can also be packaged as a library: a static library (.a on Unix, .lib on Windows) is normally searched by the linker for needed object members at link time, while a dynamic/shared library (.so, .dll) is loaded at runtime and can be shared in memory across multiple running programs at once.
Ready for the next idea?
Mark this chapter as read whenever you feel ready.