prev up next   top/contents search

comp.lang.c FAQ list · Question 10.6

Q: I'm splitting up a program into multiple source files for the first time, and I'm wondering what to put in .c files and what to put in .h files. (What does ``.h'' mean, anyway?)

A: As a general rule, you should put these things in header (.h) files:

macro definitions (preprocessor #defines)
structure, union, and enumeration declarations
typedef declarations
external function declarations (see also question 1.11)
global variable declarations

It's especially important to put a declaration or definition in a header file when it will be shared between several other files. Don't repeat a declaration or macro definition at the top of two or more source files; do put it in a header file and #include it wherever needed. The reason is not just to save typing: you want to set things up so that whenever a declaration or definition changes, you only have to change it in one place, with the update propagated to all source files consistently. (In particular, never put external function prototypes in .c files. See also question 1.7.)

On the other hand, when a definition or declaration should remain private to one .c file, it's fine to leave it there. (Private file-scope functions and variables should also be declared static. See also question 2.4.)

Finally, you should not put actual code (i.e. function bodies) or global variable definitions (that is, defining or initializing instances) in header files. Also, when you are building a project out of multiple source files, you should compile each of them separately (using a compiler option to request compilation only), and use the linker to link the resultant object files together. (In an integrated development environment, all of this may be taken care of for you.) Don't try to ``link'' all of your source files together with #include; the #include directive should be used to pull in header files, not other .c files.

See also questions 1.7, 10.7, and 17.2.

Additional links: more explanation

References: K&R2 Sec. 4.5 pp. 81-2
H&S Sec. 9.2.3 p. 267
CT&P Sec. 4.6 pp. 66-7

prev up next   contents search
about this FAQ list   about eskimo   search   feedback   copyright

Hosted by Eskimo North