Chapter 10: Organization and Documentation
Level 2 — Cognition
Structuring programs across files: interfaces, implementations, and documentation.
A program that fits in one file is a script. A program that spans dozens of files is a system. This chapter covers how C organizes code into interface and implementation, and how Auto's module system provides a cleaner alternative.
10.1 Interface Documentation
In C, the interface is declared in a header file (.h) and the implementation lives in a source file (.c). The header is a contract:
// geometry.h — interface
#ifndef GEOMETRY_H
#define GEOMETRY_H
typedef struct {
float width;
float height;
} Rectangle;
float Rectangle_area(Rectangle r);
float Rectangle_perimeter(Rectangle r);
#endif// geometry.c — implementation
#include "geometry.h"
float Rectangle_area(Rectangle r) {
return r.width * r.height;
}
float Rectangle_perimeter(Rectangle r) {
return 2.0f * (r.width + r.height);
}Other files that need Rectangle include the header:
// main.c
#include "geometry.h"
#include <stdio.h>
int main(void) {
Rectangle r = {4.0f, 6.0f};
printf("Area: %f\n", Rectangle_area(r));
return 0;
}Documentation comments. C uses /** ... */ for documentation. Many projects adopt conventions similar to Doxygen:
/**
* @brief Calculate the area of a rectangle.
* @param r The rectangle
* @return The area as a float
*/
float Rectangle_area(Rectangle r);Auto's approach. Auto replaces header files with its mod and use system. Types and their associated functions form a natural interface:
// geometry.at — both interface and implementation
type Rectangle {
width float
height float
}
fn Rectangle.new(w float, h float) Rectangle {
Rectangle(w, h)
}
fn Rectangle.area(r Rectangle) float {
r.width * r.height
}
fn Rectangle.perimeter(r Rectangle) float {
2.0 * (r.width + r.height)
}Another file uses the module with use:
This example depends on multi-file modules and cannot run inline — open it in the Playground
// main.at
use geometry
fn main() {
let r Rectangle = Rectangle.new(4.0, 6.0)
print("Area:", r.area(r))
}