计算机科学 · 第 3 册 · 本科一年级

University Computer Science — Year 1

本书暂未推出简体中文版。现有版本:English。

University Computer Science — Year 1 · 本科一年级

7Modular Programs, Makefiles and Tests

The town library’s loan checker started as a hundred lines in one file. Three years later it is six hundred lines, still in one file: dates, parsing, fines and reports mixed together. Every change recompiles everything; every function can touch every global variable; nobody knows which part a change may break, and nobody dares to touch it. This chapter gives a C program the structure that makes change safe: modules with an interface, a build that recompiles only what a change affects, and tests that say, after each change, whether the program still does what it did.

You already know

A module groups the functions that serve one purpose behind an interface, the part its users rely on; the rest can change. A specification states what a function must do; a test runs it on a chosen input and compares the result with the expected one, and a set of tests is run after every change.

7.1 Headers and implementation files

A C module is two files. The .h file declares what users may call; the .c file defines it. Users write #include "ratio.h", which the preprocessor replaces by the text of the header (Chapter 1); the compiler then knows the names and types it needs to check their calls, and the linker later joins the calls to the definitions.

Definition 7.1 (Header file, include guard)

A header file is a file of declarations (types, function prototypes, constants) meant to be included by other files. An include guard is the pair #ifndef NAME, #define NAME at its start and #endif at its end, which makes a second inclusion of the header in the same file expand to nothing.

Definition 7.2 (Interface, implementation)

The interface of a module is what its users may rely on: in C, the declarations of its header and the comments that state their contracts. Its implementation is everything else: the definitions in its .c file, which may change without any user changing.

#ifndef RATIO_H
#define RATIO_H

struct ratio;                               // an opaque type: users never see its fields

// A new fraction num/den in lowest terms, with den > 0; NULL if den == 0 or out of memory.
// The caller owns the result and frees it with ratio_free.
struct ratio *ratio_new(long num, long den);
void ratio_free(struct ratio *r);
long ratio_num(const struct ratio *r);
long ratio_den(const struct ratio *r);
struct ratio *ratio_add(const struct ratio *a, const struct ratio *b);   // a new fraction
struct ratio *ratio_mul(const struct ratio *a, const struct ratio *b);   // a new fraction
int ratio_cmp(const struct ratio *a, const struct ratio *b);             // <0, 0 or >0

#endif
Listing 7.1. The interface of a module of exact fractions code/bachelor-1/07-c-modules-make-tests/listings/ratio.h

Definition 7.3 (Opaque type)

An opaque type is a type that the interface declares without defining it, such as struct ratio; in a header whose fields appear only in the implementation file. Users can hold and pass pointers to it, but cannot read its fields, create one on the stack, or know its size: everything goes through the module’s functions.

#include <stdlib.h>
#include "ratio.h"

struct ratio {
    long num, den;                          // lowest terms, den > 0
};

static long gcd(long a, long b)             // static: invisible outside this file
{
    if (a < 0)
        a = -a;
    while (b != 0) {
        long t = a % b;
        a = b;
        b = t;
    }
    return a;
}

struct ratio *ratio_new(long num, long den)
{
    if (den == 0)
        return NULL;
    struct ratio *r = malloc(sizeof *r);
    if (r == NULL)
        return NULL;
    if (den < 0) {
        num = -num;
        den = -den;
    }
    long g = gcd(num, den);
    r->num = num / g;
    r->den = den / g;
    return r;
}

void ratio_free(struct ratio *r) { free(r); }
long ratio_num(const struct ratio *r) { return r->num; }
long ratio_den(const struct ratio *r) { return r->den; }
Listing 7.2. The implementation: the fields, a private helper, the constructor code/bachelor-1/07-c-modules-make-tests/listings/ratio.c
#include <stdio.h>
#include "ratio.h"

int main(void)
{
    struct ratio *a = ratio_new(6, -8), *b = ratio_new(1, 6);
    struct ratio *s = ratio_add(a, b), *p = ratio_mul(a, b);
    printf("a = %ld/%ld, b = %ld/%ld\n", ratio_num(a), ratio_den(a), ratio_num(b), ratio_den(b));
    printf("a + b = %ld/%ld, a * b = %ld/%ld\n", ratio_num(s), ratio_den(s), ratio_num(p), ratio_den(p));
    printf("compare(a, b) = %d, ratio_new(1, 0) = %p\n", ratio_cmp(a, b), (void *)ratio_new(1, 0));
    ratio_free(a);
    ratio_free(b);
    ratio_free(s);
    ratio_free(p);
    return 0;
}
Listing 7.3. A user that knows only the interface code/bachelor-1/07-c-modules-make-tests/listings/ratio_demo.c
$ gcc -std=c17 -O2 -Wall -Wextra -o ratio_demo ratio_demo.c ratio.c -lm && ./ratio_demo
a = -3/4, b = 1/6
a + b = -7/12, a * b = -1/8
compare(a, b) = -1, ratio_new(1, 0) = (nil)
Output 7.1. Fractions kept in lowest terms; a zero denominator refused.

The function gcd is static: its name is visible only inside ratio.c (Chapter 3), so another module may have its own gcd without a clash at link time, and no user can come to depend on it. Because the type is opaque, the module can change its representation (keep fractions unreduced, store them in long long, cache a floating value) and ratio_demo.c needs no change and no recompilation: it is only linked again with the new ratio.o. The price is one heap block per fraction and a function call per field read. The C library’s FILE is used the same way, only through pointers and library functions, as if it were opaque (its definition is in the header, but no program should read its fields); small structures such as a point are usually used directly.

7.2 Separate compilation and make

Definition 7.4 (Separate compilation)

Separate compilation is the compiling of each .c file of a program on its own into an object file (gcc -c ratio.c writes ratio.o), the object files being linked into the executable in a last step. After a change, only the object files whose sources (or included headers) changed must be compiled again.

A program’s files form a graph: each object file depends on its .c file and on the headers it includes; each executable on its object files. Deciding by hand what to recompile is error-prone; the program make does it from a description of that graph.

History — make

make was written by Stuart Feldman at Bell Laboratories. His description of it, dated August 1978, shipped with the Seventh Edition of Unix and starts from the problem of this chapter: in a large program, “a change to a declaration can obsolete a dozen other files”. Its rules, a target, the files it depends on and the commands that make it, are still those of every make in use.

Definition 7.5 (Makefile, target, prerequisite, recipe)

A makefile is a file of rules read by make. Each rule names a target, usually a file to build; its prerequisites, the files it is built from; and a recipe, the shell commands that build it, each line starting with a tab character. make builds a target when it does not exist or when one of its prerequisites, after being brought up to date itself, was modified more recently than the target.

CC = gcc
CFLAGS = -std=c17 -O2 -Wall -Wextra -Werror

all: ratio_demo ratio_test

ratio_demo: ratio_demo.o ratio.o
	$(CC) -o $@ $^

ratio_test: ratio_test.o ratio.o
	$(CC) -o $@ $^

%.o: %.c
	$(CC) $(CFLAGS) -c $<

ratio.o: ratio.h
ratio_demo.o: ratio.h
ratio_test.o: ratio.h check.h

test: ratio_test
	./ratio_test

clean:
	rm -f ratio_demo ratio_test ratio.o ratio_demo.o ratio_test.o

.PHONY: all test clean
Listing 7.4. A makefile for the module, a demo and its tests code/bachelor-1/07-c-modules-make-tests/listings/Makefile

CC and CFLAGS are variables, used as $(CC). The pattern rule %.o: %.c says how to make any object file from the .c file of the same name; in its recipe $< is the first prerequisite and, in the linking rules, $@ is the target and $^ all the prerequisites. The lines ratio.o: ratio.h add prerequisites without a recipe: the headers each object file includes. all, test and clean name no file; .PHONY says so, so that make runs them even if a file of that name exists.

$ make
gcc -std=c17 -O2 -Wall -Wextra -Werror -c ratio_demo.c
gcc -std=c17 -O2 -Wall -Wextra -Werror -c ratio.c
gcc -o ratio_demo ratio_demo.o ratio.o
gcc -std=c17 -O2 -Wall -Wextra -Werror -c ratio_test.c
gcc -o ratio_test ratio_test.o ratio.o
$ make
make: Nothing to be done for 'all'.
$ touch ratio_demo.c
$ make
gcc -std=c17 -O2 -Wall -Wextra -Werror -c ratio_demo.c
gcc -o ratio_demo ratio_demo.o ratio.o
$ touch ratio.h
$ make
gcc -std=c17 -O2 -Wall -Wextra -Werror -c ratio_demo.c
gcc -std=c17 -O2 -Wall -Wextra -Werror -c ratio.c
gcc -o ratio_demo ratio_demo.o ratio.o
gcc -std=c17 -O2 -Wall -Wextra -Werror -c ratio_test.c
gcc -o ratio_test ratio_test.o ratio.o
$ make test
./ratio_test
9 checks, 0 failed
$ make clean
rm -f ratio_demo ratio_test ratio.o ratio_demo.o ratio_test.o
Output 7.2. Five commands, then none, then two, then all five: make follows the timestamps.
The dependency graph that  describes, arrows from prerequisite to target. A change to a file must reach every file downstream of it, and only those.
The dependency graph that Listing 7.4 describes, arrows from prerequisite to target. A change to a file must reach every file downstream of it, and only those.
make after touch ratio_demo.c. Visiting the graph from the target down, it finds ratio_demo.o older than one of its prerequisites and rebuilds it; ratio_demo, now older than that new object file, is linked again; ratio.o is left alone. Shaded: the two commands of the third run.
make after touch ratio_demo.c. Visiting the graph from the target down, it finds ratio_demo.o older than one of its prerequisites and rebuilds it; ratio_demo, now older than that new object file, is linked again; ratio.o is left alone. Shaded: the two commands of the third run.

The prerequisites ratio.o: ratio.h are written by hand, and a forgotten one is a classic bug: the object file is not rebuilt after a header changes, and the program silently runs with old values (Exercise 7.5). The compiler can write these lines itself: with -MMD, compiling loans.c also writes loans.d, a makefile fragment listing the headers loans.c included, which the makefile includes (Exercise 7.11).

7.3 Unit tests in C

Definition 7.6 (Unit test, test suite)

A unit test checks one function or one module on its own, through its interface, on chosen inputs, against expected results. A test suite is the set of tests of a program, run as a whole after every change; a single failure means the change is not ready.

C has no test framework in its library. A macro of a few lines is enough to start: it counts the checks, prints each failure with its file, line and the text of the condition (#cond turns the macro’s argument into a string), and goes on, so that one run reports every failure.

#ifndef CHECK_H
#define CHECK_H
#include <stdio.h>

static int check_failures = 0, check_count = 0;

#define CHECK(cond)                                                                 \
    do {                                                                            \
        check_count++;                                                              \
        if (!(cond)) {                                                              \
            check_failures++;                                                       \
            fprintf(stderr, "%s:%d: check failed: %s\n", __FILE__, __LINE__, #cond); \
        }                                                                           \
    } while (0)

#define CHECK_REPORT()                                                              \
    (printf("%d checks, %d failed\n", check_count, check_failures), check_failures != 0)

#endif
Listing 7.5. A check that counts and goes on code/bachelor-1/07-c-modules-make-tests/listings/check.h
#include "check.h"
#include "ratio.h"

static int is(const struct ratio *r, long num, long den)
{
    return r != NULL && ratio_num(r) == num && ratio_den(r) == den;
}

int main(void)
{
    struct ratio *r[8];
    r[0] = ratio_new(6, -8);
    CHECK(is(r[0], -3, 4));                                // sign moved to the numerator
    r[1] = ratio_new(0, 5);
    CHECK(is(r[1], 0, 1));                                 // zero has one form
    CHECK(ratio_new(1, 0) == NULL);                        // the boundary of the domain
    r[2] = ratio_new(1, 6);
    r[3] = ratio_add(r[0], r[2]);
    CHECK(is(r[3], -7, 12));
    r[4] = ratio_mul(r[0], r[2]);
    CHECK(is(r[4], -1, 8));
    r[5] = ratio_new(-1, -2);
    CHECK(is(r[5], 1, 2));
    CHECK(ratio_cmp(r[0], r[2]) < 0 && ratio_cmp(r[2], r[0]) > 0);
    r[6] = ratio_new(2, 12);
    CHECK(ratio_cmp(r[2], r[6]) == 0);                     // equal values, different inputs
    r[7] = ratio_add(r[0], r[0]);
    CHECK(is(r[7], -3, 2));
    for (int i = 0; i < 8; i++)
        ratio_free(r[i]);
    return CHECK_REPORT();
}
Listing 7.6. The tests of the ratio module code/bachelor-1/07-c-modules-make-tests/listings/ratio_test.c
$ gcc -std=c17 -O2 -Wall -Wextra -o ratio_test ratio_test.c ratio.c -lm && ./ratio_test
9 checks, 0 failed
Output 7.3. Nine checks.

The test program returns a nonzero exit status when a check fails, so that make test and any script that runs it stop there. A failing test is the best bug report: it gives the input, the expected result and the place. When a bug is found, write the test that shows it first, watch it fail, then fix the code and watch it pass: the test then guards against the bug’s return. Tests are compiled with -Werror, which turns every warning into an error.

7.4 Designing tests

A test suite cannot try every input: classify below has 2962^{96} possible triples. The inputs are chosen so that every behaviour of the function is tried at least once, and every place where its behaviour changes is tried on both sides.

Definition 7.7 (Input class, boundary value)

An input class is a set of inputs that the specification treats the same way, so that one test of the class stands for all of them; the classes of a function form a partition of its domain. A boundary value is an input at the edge of a class, next to an input of another class, where off-by-one errors live.

#include "classify.h"

int classify(int a, int b, int c)
{
    if (a <= 0 || b <= 0 || c <= 0)
        return NOT_A_TRIANGLE;
    if (a + b <= c || a + c <= b || b + c <= a)
        return NOT_A_TRIANGLE;
    if (a == b && b == c)
        return EQUILATERAL;
    if (a == b || b == c || a == c)
        return ISOSCELES;
    return SCALENE;
}
Listing 7.7. The kind of a triangle with sides aa, bb and cc code/bachelor-1/07-c-modules-make-tests/listings/classify.c

The classes of classify follow from its specification: a nonpositive side; positive sides that break the triangle inequality (the longest side as aa, as bb, as cc); an equilateral triangle; isosceles with the equal pair in each of three places; scalene. The boundaries: a side equal to 0; the flat triple 1 2 3, where a+b=ca + b = c exactly. The second kind of guidance comes from the code itself.

Definition 7.8 (Control-flow graph, feasible path)

The control-flow graph of a function has a node for each block of statements executed in sequence, and an arc from a block to each block that can run next; a node with two outgoing arcs is a decision. A path runs from the entry to an exit; it is feasible if some input makes the function follow it.

Definition 7.9 (Statement, branch and path coverage)

A test suite reaches statement coverage of a function if its tests together execute every statement; branch coverage if they take every arc of every decision, both the true and the false one; path coverage if they follow every feasible path.

The control-flow graph of classify, each compound condition drawn as one decision. The three tests of the first run follow three paths; the dashed arcs are taken by none of them, so lines 7 and 13 never run.
The control-flow graph of classify, each compound condition drawn as one decision. The three tests of the first run follow three paths; the dashed arcs are taken by none of them, so lines 7 and 13 never run.

gcc --coverage adds counters to the compiled code; the program writes them to a file when it ends, and gcov turns them into a copy of the source with each line’s count, ##### marking a line never run; -b adds the branches.

$ gcc -std=c17 -O0 --coverage -c classify.c
$ gcc -std=c17 -O0 classify_run.c classify.o --coverage -o classify_run
$ ./classify_run < three.txt
3 3 3: equilateral
3 4 5: scalene
1 2 8: not a triangle
$ gcov -b classify.c | sed -n 1,5p
File 'classify.c'
Lines executed:80.00% of 10
Branches executed:100.00% of 22
Taken at least once:59.09% of 22
No calls
$ grep -E "^ +[0-9#]+: +[0-9]+:" classify.c.gcov
        3:    4:int classify(int a, int b, int c)
        3:    6:    if (a <= 0 || b <= 0 || c <= 0)
    #####:    7:        return NOT_A_TRIANGLE;
        3:    8:    if (a + b <= c || a + c <= b || b + c <= a)
        1:    9:        return NOT_A_TRIANGLE;
        2:   10:    if (a == b && b == c)
        1:   11:        return EQUILATERAL;
        1:   12:    if (a == b || b == c || a == c)
    #####:   13:        return ISOSCELES;
        1:   14:    return SCALENE;
$ sed -n 11,17p classify.c.gcov
        3:    6:    if (a <= 0 || b <= 0 || c <= 0)
branch  0 taken 100% (fallthrough)
branch  1 taken 0%
branch  2 taken 100% (fallthrough)
branch  3 taken 0%
branch  4 taken 0% (fallthrough)
branch  5 taken 100%
$ rm classify.gcda
$ ./classify_run < all.txt > /dev/null
$ gcov -b classify.c | sed -n 2,4p
Lines executed:100.00% of 10
Branches executed:100.00% of 22
Taken at least once:100.00% of 22
Output 7.4. Three tests, then twelve: 80 % of the lines and 59 % of the branches, then all of them.

gcov counts 22 branches for 4 decisions: it sees each atomic condition of a <= 0 || b <= 0 || c <= 0 as a decision of its own, because || evaluates its operands one at a time and stops at the first true one. Its branch coverage is therefore finer than that of the graph above: to take all six arcs of line 6, each of the three conditions must be true in some test where the earlier ones are false, which is what the tests 0 4 4, 4 -1 4 and 4 4 0 of the second run do. Full coverage says that every part of the code ran, not that its results were right: a coverage figure measures the tests, never the program.

7.5 Assertions, defensive programming and the debugger

Definition 7.10 (Assertion)

An assertion is a condition that the programmer states must hold at a point of the program. In C, assert(cond) from <assert.h> evaluates cond; if it is false, it prints the condition, the file, the line and the function on standard error and stops the program with abort. If the macro NDEBUG is defined, every assert expands to nothing.

#include <assert.h>
#include <stdio.h>

double mean(const double *x, int n)
{
    assert(n > 0);                          // a caller's error, not a run-time condition
    double s = 0.0;
    for (int i = 0; i < n; i++)
        s += x[i];
    return s / n;
}

int main(void)
{
    double rain[3] = {1.0, 2.5, 0.0};
    printf("mean of 3: %.2f\n", mean(rain, 3));
    printf("mean of 0: %.2f\n", mean(rain, 0));
    return 0;
}
Listing 7.8. A precondition stated as an assertion code/bachelor-1/07-c-modules-make-tests/listings/assert_demo.c
$ gcc -std=c17 -O2 assert_demo.c -o assert_demo
$ { ./assert_demo 2>&1; } 2>/dev/null; echo "exit status $?"
assert_demo: assert_demo.c:7: mean: Assertion `n > 0' failed.
exit status 134
$ gcc -std=c17 -O2 -DNDEBUG assert_demo.c -o assert_demo
$ ./assert_demo; echo "exit status $?"
mean of 3: 1.17
mean of 0: -nan
exit status 0
Output 7.5. With the check, a clear stop; without it, NaN printed as a mean.

Exit status 134 is 128+6128 + 6, the number of the signal sent by abort. Built with -DNDEBUG, the program divides 0 by 0 and prints -nan, “not a number”, the floating-point result of 0/00/0, as if it were a mean.

Definition 7.11 (Defensive programming)

Defensive programming is writing each function so that it detects the situations it was not designed for, instead of computing garbage from them: it checks what it receives from outside the program and returns an error, and it asserts what its callers must guarantee.

Method 7.12 (Assertion or error return)

  1. If the situation can happen in a correct program (a file that does not exist, a line badly typed by a person, a malloc that fails), return an error and let the caller decide: date_parse returns −1-1.
  2. If it can happen only through a bug of the program (a month 13 passed to days_in_month after the date was validated, a mean of no values), assert it: the program stops at the bug, with its location, instead of propagating a wrong value.
  3. Never put in an assertion an expression whose effect the program needs, such as assert(p = malloc(n)): with NDEBUG, the call disappears.

When a program crashes, the first question is where. Compiled with -g, the program carries the line numbers of its source, and the address sanitizer prints the chain of calls that led to the faulty access, its backtrace.

#include <stdio.h>
#include <string.h>

struct station {
    const char *name;
    struct station *next;
};

int altitude_rank(const struct station *s, const char *name)
{
    int rank = 0;
    while (strcmp(s->name, name) != 0) {    // no test for the end of the list
        s = s->next;
        rank++;
    }
    return rank;
}

int main(void)
{
    struct station r = {"Riverside", NULL}, h = {"Hilltop", &r};
    printf("Riverside: %d\n", altitude_rank(&h, "Riverside"));
    fflush(stdout);
    printf("Harbour: %d\n", altitude_rank(&h, "Harbour"));
    return 0;
}
Listing 7.9. A search that does not stop at the end of the list code/bachelor-1/07-c-modules-make-tests/listings/crash.c
$ gcc -std=c17 -O0 -g -fsanitize=address crash.c -o crash
$ { ./crash 2>&1 | grep -E "^Riverside|ERROR|caused|#[0-2] "; } 2>/dev/null
Riverside: 1
==1000==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000000 (pc 0x555555555300 bp 0x7fffffffec00 sp 0x7fffffffebe0 T0)
==1000==The signal is caused by a READ memory access.
    #0 0x555555555300 in altitude_rank ~/session/crash.c:13
    #1 0x5555555554e2 in main ~/session/crash.c:25
    #2 0x7ffff7029d8f  (/lib/x86_64-linux-gnu/libc.so.6+0x29d8f)
Output 7.6. The crash, the access, and the two frames that matter.

Definition 7.13 (Debugger, breakpoint)

A debugger is a program that runs another program under its control: it can stop it, execute it one line at a time, show and change its variables, and print the chain of active calls. A breakpoint is a place in the program, usually a line, where the debugger stops it before executing that place.

A debugging session on , as a sequence of commands. The program is built with -g -O0, so that each line of the source maps to machine instructions in order.
A debugging session on Listing 7.9, as a sequence of commands. The program is built with -g -O0, so that each line of the source maps to machine instructions in order.

A typical session on the crash above, with a debugger such as the GNU debugger: set a breakpoint on line 13, start the program, and it stops before the first comparison of the first call, the search for Riverside. Continue: that call ends (the program prints Riverside: 1) and the debugger stops again in the second call, the search for Harbour. Print s->name and see Hilltop; step, and see s move to Riverside, then to the null pointer; at the next step the program receives its signal, and the backtrace command prints the two frames of the sanitizer’s report. A debugger answers questions that a crash report cannot: what a variable held three lines before, which branch was taken. No debugger is installed on the machine that ran this book’s programs, so this one is told, not shown; the sanitizer’s backtrace above is available wherever the compiler is.

Safe use

Keep assertions on in tests and in development builds. Give every module its own test file, run the whole suite before every change is kept, and add a test for each bug fixed. Build with -Wall -Wextra -Werror, with the address sanitizer for tests, and with -g whenever a crash must be located.

7.6 Exercises

Exercise 7.1 ★

With the makefile of Listing 7.4, after a full build, which commands does make run after editing check.h? After editing ratio.c?

Solution

Solution of Exercise 7.1.

check.h is a prerequisite of ratio_test.o only: make compiles ratio_test.c and links ratio_test, two commands. After editing ratio.c: compile it, then link both executables, three commands.

Exercise 7.2 ★

Does the test set {(4,0),(70,0)}\{(4, 0), (70, 0)\} reach statement coverage of fare? Which single test makes it reach statement coverage, and does the set then reach branch coverage?

int fare(int age, int student)
{
    int price = 300;
    if (age < 6)
        price = 0;
    else if (age < 18 || student)
        price = 150;
    if (age >= 65)
        price = 200;
    return price;
}
Listing 7.10. A bus fare code/bachelor-1/07-c-modules-make-tests/listings/exo_fare.c
Solution

Solution of Exercise 7.2.

No: neither test makes age < 18 || student true without age < 6, so price = 150 never runs. Adding (30,1)(30, 1) (or any age from 6 to 17) runs it. The three tests then take both arcs of each decision: age < 6 is true for 4 and false for 70; the second condition is true for (30,1)(30, 1) and false for (70,0)(70, 0); age >= 65 is true for 70 and false for 4. Branch coverage is reached, counting each if as one decision.

Exercise 7.3 ★

What does this program print, on which stream, and with which exit status? What if it is compiled with -DNDEBUG?

#include <assert.h>
#include <stdio.h>

int percent(int part, int whole)
{
    assert(whole > 0 && part >= 0 && part <= whole);
    return 100 * part / whole;
}

int main(void)
{
    printf("%d%%\n", percent(87, 400));
    printf("%d%%\n", percent(22, 0));
    return 0;
}
Listing 7.11. A precondition code/bachelor-1/07-c-modules-make-tests/listings/exo_assert.c
Solution

Solution of Exercise 7.3.

The first call computes 100×87/400=21100 \times 87 / 400 = 21 in integer division, and printf sends 21 and a percent sign to standard output; the second fails the assertion, which prints its message on standard error and stops the program with exit status 134. As the output is a pipe here, the line 21% sat in the buffer of stdout and was lost when abort stopped the program: only the message appears. With -DNDEBUG, percent(22, 0) divides by zero, which is undefined behaviour (on this machine, the program is stopped by a signal).

$ gcc -std=c17 -O2 exo_assert.c -o exo_assert
$ { ./exo_assert 2>&1; } 2>/dev/null; echo "exit status $?"
exo_assert: exo_assert.c:7: percent: Assertion `whole > 0 && part >= 0 && part <= whole' failed.
exit status 134
Output 7.10. The run.

Exercise 7.4 ★

point.h has no include guard. Explain the compiler’s error, and add the guard.

#include "point.h"

struct segment {
    struct point a, b;
};
Listing 7.12. segment.h includes point.h code/bachelor-1/07-c-modules-make-tests/listings/segment.h
#include "point.h"
#include "segment.h"

int main(void)
{
    struct segment s = {{0, 0}, {3, 4}};
    struct point p = s.b;
    return (int)p.x;
}
Listing 7.13. So does the program code/bachelor-1/07-c-modules-make-tests/listings/exo_guard.c
point.h:2:8: error: redefinition of 'struct point'
point.h:2:8: note: originally defined here
Output 7.7. The error. Some lines are left out.
Solution

Solution of Exercise 7.4.

exo_guard.c includes point.h, then segment.h, which includes it again: struct point is defined twice in the same file, an error. Put #ifndef POINT_H, #define POINT_H before the definition and #endif after it: the second inclusion then finds POINT_H defined and skips the text.

Exercise 7.5 ★★

A colleague raised the limit in config.h from 3 to 5, ran make, and the program still says 3. Find the missing line of the makefile.

limits: limits_main.o
	gcc -o limits limits_main.o

limits_main.o: limits_main.c
	gcc -std=c17 -O2 -c limits_main.c
Listing 7.14. A makefile with a missing prerequisite code/bachelor-1/07-c-modules-make-tests/listings/stale.Makefile
$ make -f stale.Makefile && ./limits
gcc -std=c17 -O2 -c limits_main.c
gcc -o limits limits_main.o
a member may borrow 3 books
$ sed -i "s/MAX_LOANS 3/MAX_LOANS 5/" config.h
$ make -f stale.Makefile && ./limits
make: 'limits' is up to date.
a member may borrow 3 books
Output 7.8. A stale build.
Solution

Solution of Exercise 7.5.

limits_main.o depends on config.h, which it includes, but the rule does not say so: make sees an object file newer than limits_main.c and does nothing. The rule must be limits_main.o: limits_main.c config.h, or the dependencies written by the compiler (Exercise 7.11).

Exercise 7.6 ★★

The function max3 has a bug, and its four tests pass. Find the bug, a test that reveals it, and what is wrong with the four tests.

#include "check.h"

int max3(int a, int b, int c)
{
    int m = a;
    if (b > m)
        m = b;
    if (c > a)
        m = c;
    return m;
}

int main(void)
{
    CHECK(max3(1, 2, 3) >= 1);
    CHECK(max3(1, 9, 5) >= 5);
    CHECK(max3(4, 9, 1) >= 4);
    CHECK(max3(2, 2, 2) >= 2);
    return CHECK_REPORT();
}
Listing 7.15. A green report code/bachelor-1/07-c-modules-make-tests/listings/exo_max3.c
Solution

Solution of Exercise 7.6.

The second if compares c with a instead of m: for max3(1, 9, 5), m becomes 9, then 5 > 1 replaces it by 5. The checks only say that the result is at least some argument, which a wrong result can satisfy: 5 >= 5 passes. A test must compare with the exact expected value: CHECK(max3(1, 9, 5) == 9) fails, as it should.

$ gcc -std=c17 -O2 -Wall -Wextra -o exo_max3 exo_max3.c -lm && ./exo_max3
4 checks, 0 failed
Output 7.11. Green, and wrong.

Exercise 7.7 ★★

Write a module stack of int: an opaque struct stack, stack_new, stack_free, stack_push, stack_pop (which reports an empty stack) and stack_size, with its header and a test file that covers the empty stack and a stack that grows past its first capacity.

Solution

Solution of Exercise 7.7.

struct stack {
    int *data;
    size_t len, cap;
};

struct stack *stack_new(void)
{
    return calloc(1, sizeof(struct stack));
}

void stack_free(struct stack *s)
{
    if (s != NULL)
        free(s->data);
    free(s);
}

int stack_push(struct stack *s, int v)
{
    if (s->len == s->cap) {
        size_t cap = s->cap == 0 ? 4 : 2 * s->cap;
        int *bigger = realloc(s->data, cap * sizeof *bigger);
        if (bigger == NULL)
            return -1;
        s->data = bigger;
        s->cap = cap;
    }
    s->data[s->len++] = v;
    return 0;
}

int stack_pop(struct stack *s, int *v)
{
    if (s->len == 0)
        return -1;
    *v = s->data[--s->len];
    return 0;
}

size_t stack_size(const struct stack *s) { return s->len; }
A stack behind an opaque type code/bachelor-1/07-c-modules-make-tests/exercises/stack.c

The test tests/stack_test.c pops an empty stack, pushes 100 values (past the first capacities 4, 8, …), pops them in reverse order, and frees a null pointer.

Exercise 7.8 ★★

Give a set of tests that reaches branch coverage of late_fee, counting each atomic condition of && as a decision, and add the boundary of “more than 30 days”.

int late_fee(int days_late, int member_years)
{
    if (days_late <= 0)
        return 0;
    int fee = 10 * days_late;
    if (days_late > 30 && member_years < 5)
        fee += 200;
    if (fee > 500)
        fee = 500;
    return fee;
}
Listing 7.16. A late fee, in cents code/bachelor-1/07-c-modules-make-tests/exercises/late_fee.c
Solution

Solution of Exercise 7.8.

(0, 1): the first decision true. (3, 1): first false, days_late > 30 false, cap false. (31, 2): both conditions of && true, and the cap true (510 becomes 500). (31, 7): the left condition true, the right one false. These four take every arc, each atomic condition counted. The boundary: (30, 1) gives 300 without surcharge, and (31, 2) is on the other side. The test is tests/late_fee_test.c.

Exercise 7.9 ★★

A decision is c1 && c2 && ... && ck. How many tests try every combination of the kk conditions? Show that k+1k + 1 tests suffice for each condition to be shown, by a pair of tests differing only in that condition, to change the outcome on its own. (This criterion, a form of modified condition/decision coverage, is told here, not developed.)

Solution

Solution of Exercise 7.9.

Every combination: 2k2^k tests. The k+1k + 1 tests: all conditions true (outcome true), and for each ii the test where only cic_i is false (outcome false). Each of the last kk differs from the first in cic_i alone, and the outcome changes, so cic_i is shown to matter on its own. The test tests/test_conditions.py checks this for k≤7k \leq 7.

Exercise 7.10 ★★★

In the makefile of the weekend problem, compute, for each of the seven source files, the set of targets that a plain make, which builds the default target checker, rebuilds after an edit to that file, using only the graph of the rules. Explain why the answer is the set of targets reachable from the edited file on the way to checker.

Solution

Solution of Exercise 7.10.

make rebuilds a target when a prerequisite is newer, and a target it rebuilds becomes newer than the targets that depend on it: the rebuilding spreads along the arcs, from the edited file to every target reachable from it, and to no other. date.h: date.o, loans.o, loans_main.o, checker; date.c: date.o, checker; csv.h: csv.o, loans.o, checker; csv.c: csv.o, checker; loans.h: loans.o, loans_main.o, checker; loans.c and loans_main.c: their object file and checker. The test tests/test_conditions.py computes these sets. The date_test.o and date_test rules are also reachable from date.h (and date_test from date.c), but they are not on the way to checker: a plain make leaves them alone, and make test rebuilds them.

Exercise 7.11 ★★★

Write a makefile for the four modules of the weekend problem with a single pattern rule, a variable listing the sources, and header dependencies written by the compiler with -MMD -MP. Show that touching csv.h rebuilds exactly csv.o and loans.o.

Solution

Solution of Exercise 7.11.

CC = gcc
CFLAGS = -std=c17 -O2 -Wall -Wextra -Werror -MMD -MP
SRC = loans_main.c loans.c csv.c date.c
OBJ = $(SRC:.c=.o)

checker: $(OBJ)
	$(CC) -o $@ $^

%.o: %.c
	$(CC) $(CFLAGS) -c $<

clean:
	rm -f checker $(OBJ) $(OBJ:.o=.d)

.PHONY: clean
-include $(OBJ:.o=.d)
Dependencies written by the compiler code/bachelor-1/07-c-modules-make-tests/listings/mmd.Makefile
gcc -o checker loans_main.o loans.o csv.o date.o
$ cat loans.d
loans.o: loans.c csv.h loans.h date.h
csv.h:
loans.h:
date.h:
$ touch csv.h
$ make -f mmd.Makefile
gcc -std=c17 -O2 -Wall -Wextra -Werror -MMD -MP -c loans.c
Output 7.12. The fragment written for loans.o, and the rebuild after touching csv.h. Some lines are left out.

The -include line reads the .d files, and ignores them before the first build. The empty rules added by -MP keep make from failing if a header is later deleted.

Exercise 7.12 ★★★

Suppose that every statement of a function lies on some feasible path, and that every decision has two outgoing arcs. Prove that a test set reaching branch coverage reaches statement coverage. Give a function and a test set that reach statement coverage but not branch coverage.

Solution

Solution of Exercise 7.12.

Take any statement. It lies on a feasible path; let DD be the last decision before it on that path, if any. If there is none, every test executes it. Otherwise the statement lies on the arc of DD that the path takes, before the next decision, and branch coverage means some test takes that arc, and so executes the statement. Converse: the function int f(int x) { int y = 0; if (x > 0) y = 1; return y; } reaches statement coverage with the single test x=1x = 1, which never takes the false arc of the if.

7.7 Problem: Taming a one-file program

Problem 7.1

Weekend problem — Taming a one-file program

The library’s loan checker has been split into four modules: date (calendar arithmetic), csv (splitting a line), loans (a loan and its delay) and loans_main.c (the program). It reads the town’s loans.csv and a date, and reports the loans that were or are late at that date. The tests of the date module were written from input classes; the date module’s first version, date_v0.c, differs from the current one in one line of code.

#ifndef DATE_H
#define DATE_H

struct date {
    int year, month, day;
};

int is_leap(int year);
int days_in_month(int year, int month);              // month from 1 to 12
int date_parse(const char *s, struct date *d);       // "YYYY-MM-DD", year >= 1970: 0, or -1
long days_between(struct date a, struct date b);     // b - a, in days

#endif
Listing 7.17. The date module’s interface code/bachelor-1/07-c-modules-make-tests/listings/date.h
int is_leap(int year)
{
    return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
}

int days_in_month(int year, int month)
{
    static const int length[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    assert(month >= 1 && month <= 12);               // the caller's duty
    return month == 2 && is_leap(year) ? 29 : length[month - 1];
}

int date_parse(const char *s, struct date *d)
{
    int y, m, dd;
    char extra;
    if (sscanf(s, "%4d-%2d-%2d%c", &y, &m, &dd, &extra) != 3)
        return -1;                                   // too few fields, or something after the day
    if (y < 1970 || m < 1 || m > 12 || dd < 1 || dd > days_in_month(y, m))
        return -1;
    *d = (struct date){y, m, dd};
    return 0;
}

static long days_since_1970(struct date d)
{
    long n = 0;
    for (int y = 1970; y < d.year; y++)
        n += is_leap(y) ? 366 : 365;
    for (int m = 1; m < d.month; m++)
        n += days_in_month(d.year, m);
    return n + d.day - 1;
}

long days_between(struct date a, struct date b)
{
    return days_since_1970(b) - days_since_1970(a);
}
Listing 7.18. Its implementation code/bachelor-1/07-c-modules-make-tests/listings/date.c
#ifndef LOANS_H
#define LOANS_H
#include "date.h"

struct loan {
    int id, book, member;
    struct date out, due, back;
    int returned;                                    // 0 while the book is out
};

int loan_parse(char *line, struct loan *l);          // a line of loans.csv: 0, or -1
long loan_days_late(const struct loan *l, struct date today);   // 0 if not late

#endif
Listing 7.19. The loans module’s interface code/bachelor-1/07-c-modules-make-tests/listings/loans.h
CC = gcc
CFLAGS = -std=c17 -O2 -Wall -Wextra -Werror

checker: loans_main.o loans.o csv.o date.o
	$(CC) -o $@ $^

%.o: %.c
	$(CC) $(CFLAGS) -c $<

date.o: date.h
csv.o: csv.h
loans.o: loans.h date.h csv.h
loans_main.o: loans.h date.h

date_test: date_test.o date.o
	$(CC) -o $@ $^

date_test.o: date.h check.h

test: date_test
	./date_test

.PHONY: test
Listing 7.20. The makefile code/bachelor-1/07-c-modules-make-tests/listings/library.Makefile
static long between(const char *a, const char *b)
{
    struct date x, y;
    if (date_parse(a, &x) != 0 || date_parse(b, &y) != 0)
        return -999999;
    return days_between(x, y);
}

int main(void)
{
    CHECK(!is_leap(2025) && is_leap(2024));            // ordinary years
    CHECK(!is_leap(1900) && !is_leap(2100));           // centuries
    CHECK(is_leap(2000) && is_leap(2400));             // every fourth century
    CHECK(days_in_month(2025, 2) == 28 && days_in_month(2024, 2) == 29);
    CHECK(days_in_month(2025, 1) == 31 && days_in_month(2025, 12) == 31 && days_in_month(2025, 4) == 30);
    struct date d;
    CHECK(date_parse("2025-06-14", &d) == 0 && d.year == 2025 && d.month == 6 && d.day == 14);
    CHECK(date_parse("2025-02-29", &d) == -1);         // not a leap year
    CHECK(date_parse("2024-02-29", &d) == 0);
    CHECK(date_parse("2025-13-01", &d) == -1 && date_parse("2025-00-10", &d) == -1);
    CHECK(date_parse("2025-04-31", &d) == -1 && date_parse("2025-04-00", &d) == -1);
    CHECK(date_parse("1969-12-31", &d) == -1);         // before the domain
    CHECK(date_parse("2025-06-14x", &d) == -1 && date_parse("2025-06", &d) == -1);
    CHECK(between("2025-01-22", "2025-01-22") == 0);
    CHECK(between("2025-01-22", "2025-01-03") == -19);
    CHECK(between("2025-12-31", "2026-01-01") == 1);   // across a year
    CHECK(between("2024-02-28", "2024-03-01") == 2);   // across a leap day
    CHECK(between("1970-01-01", "2000-01-01") == 10957);
    CHECK(between("2099-02-28", "2100-03-01") == 366); // 2100 is not a leap year
    return CHECK_REPORT();
}
Listing 7.21. The tests of the date module code/bachelor-1/07-c-modules-make-tests/listings/date_test.c
$ make -f library.Makefile
gcc -std=c17 -O2 -Wall -Wextra -Werror -c loans_main.c
gcc -std=c17 -O2 -Wall -Wextra -Werror -c loans.c
gcc -std=c17 -O2 -Wall -Wextra -Werror -c csv.c
gcc -std=c17 -O2 -Wall -Wextra -Werror -c date.c
gcc -o checker loans_main.o loans.o csv.o date.o
$ ./checker loans.csv 2025-12-31
400 loans, 22 still out, 109 late, 5285 late days in all
member 57 has the most late days: 485
$ for f in date.h date.c csv.h csv.c loans.h loans.c loans_main.c; do touch $f; echo "$f: $(make -f library.Makefile | grep -c -- " -c ")"; done
date.h: 3
date.c: 1
csv.h: 2
csv.c: 1
loans.h: 2
loans.c: 1
loans_main.c: 1
$ make -f library.Makefile test
gcc -std=c17 -O2 -Wall -Wextra -Werror -c date_test.c
gcc -o date_test date_test.o date.o
./date_test
18 checks, 0 failed
$ gcc -std=c17 -O0 --coverage -c date.c -o date.o && gcc date_test.c date.o --coverage -o cov_test
$ ./cov_test && gcov -b date.c | sed -n 2,4p
18 checks, 0 failed
Lines executed:100.00% of 21
Branches executed:100.00% of 32
Taken at least once:93.75% of 32
$ cp date_v0.c date.c
$ make -f library.Makefile test 2>&1 | grep -v "^gcc"
./date_test
date_test.c:17: check failed: !is_leap(1900) && !is_leap(2100)
date_test.c:34: check failed: between("2099-02-28", "2100-03-01") == 366
18 checks, 2 failed
make: *** [library.Makefile:22: test] Error 1
Output 7.9. Building, running, counting the compiler runs after an edit to each file, testing, measuring coverage, and testing the first version.

Part I — Modules and interfaces.

  1. Draw the dependency graph of the checker: the seven source files, the four object files and the executable.
  2. loans.h includes date.h. Why must it, and why does loans.h not include csv.h?
  3. days_since_1970 is static and absent from date.h. Give two reasons.
  4. struct date is not opaque, unlike struct ratio. What would making it opaque cost the users of the module, and what would it gain?
  5. Which modules could be reused, unchanged, by a program that reads the weather file?
  6. The comment of csv_split states its contract. Which part of it tells a caller that an empty last field (a loan not returned) produces a field, and why does that matter to loan_parse?

Part II — The makefile and the rebuilds it saves.

  1. The first build runs five commands. Which are compilations and which is a link?
  2. Explain each of the seven counts printed by the loop, from the graph of question 1.
  3. Without make, a safe rebuild compiles the four .c files after any edit. Over one edit to each of the seven files, how many compilations is that, and how many did make perform?
  4. The rule loans_main.o: loans.h date.h lists date.h, which loans_main.c does not include itself. Is the line wrong?
  5. Remove date.h from the rule of loans.o. Which edit would then produce a stale build, and what could the stale program do wrong?
  6. date_test is not part of the default target. What does that change in the counts of question 8?

Part III — Tests from classes and boundaries.

  1. List the input classes of is_leap implied by the Gregorian rule, with one year of each from the tests.
  2. Which tests of date_parse are boundary values? Name the boundary of each.
  3. Recompute between("1970-01-01", "2000-01-01") == 10957.
  4. The coverage run reaches every line and 30 of the 32 branches. Which two branches are never taken, and why can no correct caller take them?
  5. The checker reports 400 loans, 22 still out, 109 late and 5285 late days at 2025-12-31. Which of these numbers does the test suite check?
  6. The date tests were written before the checker existed. Name one way in which they could still pass while the checker gives a wrong total.

Part IV — Defensive checks and a bug found by a test.

  1. The first version fails two checks. Which line of date_v0.c differs, and why do both failures come from it?
  2. On the town’s file, which covers 2025 only, does the first version give a different report? Why was the bug found anyway?
  3. days_in_month asserts that the month lies in 1 to 12, but date_parse returns −1-1 for month 13. Explain this division of labour with the method of the chapter.
  4. loans_main.c rejects a member number of 1000 or more. Is that a check or an assertion, and why?
  5. What does the checker print, and with what exit status, if the date argument is 2025-02-29?
  6. State the named result of the problem, the rebuild saving.
Solution

Solution of Problem 7.1.

1. date.o on date.c, date.h; csv.o on csv.c, csv.h; loans.o on loans.c, loans.h, date.h, csv.h; loans_main.o on loans_main.c, loans.h, date.h; checker on the four object files.

2. struct loan has fields of type struct date, whose size the compiler must know. The interface of loans never mentions csv: splitting is a detail of its implementation, so csv.h is included in loans.c only, and users of loans.h do not depend on it.

3. It is a detail (another implementation might count from another day), and keeping it private leaves the module free to change it; its name cannot clash with a function of the same name elsewhere.

4. Opaque, a date would live on the heap, be created and freed by calls, and be read through functions: more code, more allocations, and struct loan could hold only pointers. The gain: the representation could change (a day count instead of three fields) without recompiling users. For three small integers, the cost wins.

5. date and csv: neither mentions loans.

6. “Empty fields included”: a line ending with a comma yields a last field that is an empty string, so loan_parse gets six fields and reads “not returned” from the empty sixth one.

7. Four compilations (-c), then the link of checker.

8. date.h is included by date.c, loans.c (through loans.h as well) and loans_main.c (through loans.h): 3. csv.h: csv.o and loans.o, 2. loans.h: loans.o and loans_main.o, 2. Each .c file: its own object file, 1.

9. 7×4=287 \times 4 = 28 compilations against 3+1+2+1+2+1+1=113 + 1 + 2 + 1 + 2 + 1 + 1 = 11.

10. No: loans_main.c includes loans.h, which includes date.h, so a change to date.h can change the meaning of loans_main.c. The prerequisites are the headers included directly or indirectly.

11. An edit to date.h that changes struct date (a field added, say) would leave loans.o compiled with the old layout while date.o uses the new one: the two would read the same bytes as different fields, and the program would compute wrong delays without any error.

12. Nothing: the counts concern the target checker. With date_test in the default target, an edit to date.h or date.c would add one compilation (date_test.o for the first) and one link.

13. Years not divisible by 4 (2025); divisible by 4 but not by 100 (2024); divisible by 100 but not by 400 (1900, 2100); divisible by 400 (2000, 2400).

14. 2025-02-29 and 2024-02-29 (the last day of February, each side of the leap rule); 2025-13-01 and 2025-00-10 (the months 1 and 12); 2025-04-31 and 2025-04-00 (the days 1 and 30 of a 30-day month); 1969-12-31 (the start of the domain); 2025-12-31 to 2026-01-01 (a year’s end).

15. From 1970 to 1999: 30 years, of which 1972, 1976, …, 1996 are leap years, 7 of them; 30×365+7=10 95730 \times 365 + 7 = 10\,957.

16. The two arcs of the assertion in days_in_month that lead to its failure (month >= 1 false, month <= 12 false). Every caller passes a valid month: date_parse checks it first, and the loop of days_since_1970 runs from 1 to 11. A failing assertion would mean a bug in the module.

17. None of them: the suite tests the date module only. The figures are produced by the whole program on the real file, and only a test of loans and loans_main (or a comparison with a count made another way) would check them.

18. loan_days_late might use out instead of due, or loans_main.c might skip the last line of the file: the dates would be right and the total wrong. Unit tests of one module say nothing of the modules around it.

19. is_leap returns year % 4 == 0, which makes 1900 and 2100 leap years. The check of line 17 calls is_leap(2100) directly; the check of line 34 counts 367 days from 2099-02-28 to 2100-03-01, because the first version gives February 2100 a 29th day.

20. No: between 2025 and 2026 the two rules agree, every year from 1901 to 2099 being leap exactly when divisible by 4. The bug was found because the tests were chosen from the classes of the specification, not from the data: the class “divisible by 100 but not by 400” had a test.

21. A month 13 can come from outside the program (a typing error in the file): date_parse must expect it and return an error. Once a date is parsed, a month 13 can only come from a bug: days_in_month asserts.

22. A check: the number comes from the file, written by people and other programs. The checker reports the line and stops with an error status.

23. date_parse rejects 2025-02-29, so main prints its usage line on standard error and returns 2.

24. The rebuild saving. With the four modules and the dependencies of Listing 7.20, one edit to each of the seven source files costs 3+1+2+1+2+1+1=113 + 1 + 2 + 1 + 2 + 1 + 1 = 11 compiler runs instead of 7×4=287 \times 4 = 28 for full rebuilds: an edit to a file costs as many compilations as there are object files reachable from it in the dependency graph, and make counted exactly those.

本章定义的术语

在术语表中查看全部 1050 个术语