Headers include multiple C files

I have two files foo.c and bar.c, which I compile separately with gcc -c, and then a link. Both files need the stdio.h and stdlib.h headers.

Should I include them in both? Doesn't feel a little redundant? Should I use #ifdef?

What is the best practice?

+5
source share
5 answers

Each C file is a different translation unit. In other words, it is a whole separate program, syntactically complete and correct. Thus, each C file must be compiled independently of any other C file and must contain every declaration for each identifier used, regardless of whether these declarations appear in other C files. From the point of view of the compiler, each C file is a complete program in itself (albeit with unauthorized links).

Header files typically contain files containing ads that should be displayed in file group C. Header files can be included with a preprocessor, which is a plain text copy and pasted at an included point, as a convenience to avoid manually duplicating ads between translation units.

: C - .

( , , . , . , - , .)

+16

. - . , , .

+2

( ) #ifndef, ( - → foo.h bar.h bar.h foo.h).

"" ( , ), ( ) . foo.c bar.c.

+1

, , .
#ifdef, .

0

, . ++, .cpp , , .h , . .h.

, , .h, , . .

.h, , , " ". #ifdef, . , . , foo.h bar.h .

0

All Articles