There exists a header file for almost each .c file in my project. All typedefs and function declarations are placed in header files. But is this a good practice? Some of the typedefs are used only in one of the .c files. Also some of the functions are not called by functions in other source files.
-
7If they're not used anywhere else (i.e. they're "private") then there is no reason to declare them in a header file. – Oliver Charlesworth May 29 '18 at 21:20
-
3And functions and "global" variables that truly are only applicable within the .c module could be declared static. – lurker May 29 '18 at 21:29
1 Answers
#include
is a pre-processing step, so you can stick whatever in there. This is largely a question of style, but it is good programming practice to minimise the impact on the namespace. (Usually) using header files allows a primitive distinction between public and private, with the public definitions being put in the header. That way, a separate compilation unit can include the header and have the definitions resolved when one links them. Anything that is private to the compilation unit should not be included unless a public declaration has it as it's dependency. Some things that are useful (or essential) to put in header files,
typedef
's that are used in public functions, (eg, a pointer-to-function used as an argument to a non-static
function that is also part of the header);enum
values that are used in public functions or are part of the.h
file's purpose;struct
orunion
declarations, especially if they are in public functions. One does not need to define them if all functions use pointer values, (data hiding is good design, see What is the difference between a definition and a declaration?);#define
in header files should be used sparingly to avoid namespace conflicts, but sometimes it's part of the header's purpose;- any private symbols should be
static
, thus eligible for extra optimisation; anythingstatic
should not be there, andmain
does not need a prototype, (see Declare main prototype); extern
see C: What is the use of 'extern' in header files?.
The c
file should generally #include
it's h
file. There are some other uses of header files, too; for example, see https://en.wikipedia.org/wiki/X_Macro.

- 1,767
- 2
- 16
- 22