A program in several files
Until now every program lived in one .c file. As a file grows, it gets hard to find anything in it. And when a second program needs the same functions, a copy means two places to fix the same bug. That's why a program is split into modules.
A module is two files:
daytime.h(a header file) – what the module can do: the list of functions, the constants and their descriptions. It is the contract for whoever uses the module.daytime.c– how: the function bodies.
Declaration and definition
int to_minutes(int hour, int min); /* declaration */
int to_minutes(int hour, int min) { /* definition */
assert(is_time(hour, min));
return hour * 60 + min;
}
A declaration ("deklaracija") gives the name, the parameters and the return type, with a semicolon instead of a body. A definition ("apibrėžimas") has the body. You may declare a function several times, but define it exactly once in the whole program. Until now you wrote functions above main, so the definition was also the declaration.
How a program of several files is built
- The preprocessor carries out
#include: it simply pastes in the text of the named file. - The compiler translates each
.cfile separately into an object file (.o;.objin CLion on Windows). While translatingmain.cit sees only the declarations fromdaytime.h, and they are enough to check that a function is called correctly. - The linker joins the object files and libraries into one program and finds the definition for every call.
So errors come in two kinds: the compiler's (in one file) and the linker's (across the whole program). In step 5 you'll cause both.
What goes into a .h
- function declarations;
- constants (
#define) that users need; - descriptions: the contracts, and from step 6 Doxygen.
Not: function bodies and variables. A .h is pasted into several .c files, so a body in it would turn into several definitions.
Every .h is wrapped in an include guard:
#ifndef DAYTIME_H
#define DAYTIME_H
/* ... deklaracijos ... */
#endif
The first time, DAYTIME_H isn't defined yet, so the contents are pasted in and DAYTIME_H gets defined. If the same file is included a second time (e.g. through another .h), the whole contents are skipped. You already saw such a guard in hw/05/numbers.h.
#include "..." and #include <...>
#include "daytime.h"– a project file: searched next to the.cfile and in the project's folders.#include <stdio.h>– the standard library.
A module's .c file includes its own .h first. Then the compiler checks that the declarations match the definitions: if the .h says int and the .c says double, you get conflicting types.
static: for this file only
A function needed only inside the module is written with static:
static int nearly_equal(double a, double b) {
return a - b < 0.000001 && b - a < 0.000001;
}
It isn't in the .h file and other files can't see it, so another module may have its own nearly_equal. Without static, two functions with the same name in two files are a linker error: multiple definition.