Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansi C - programming language book of K&R - header file inclusion

Going through the K&R ansi C programming language book (second version), on page 82 an example is given for a programming files/folders layout.

Copyright K&R - C programming language - Ansi C second edition

What I don't understand is, while calc.h gets included in main (use of functions), getop.c (definition of getop) and stack.c (definition of push and pop), it does not get included into getch.c, even though getch and ungetch are defined there.

like image 786
hewi Avatar asked Dec 01 '15 08:12

hewi


2 Answers

Although it's a good idea to include the header file it's not required as getch.c doesn't actually use the function declared in calc.h, it could even get by if it only used those already defined in getch.c.

The reason it's a good idea to include the header file anyway is because it would provide some safety if you use modern style prototypes and definitions. The compiler should namely complain if for example getop isn't defined in getop.c with the same signature as in calc.h.

like image 128
skyking Avatar answered Oct 20 '22 18:10

skyking


calc.h contains the declaration of getch() and ungetch(). It is included by files that want to use these functions (and, therefore, need their signature).

getch.c, instead, contains the definition of getch() and ungetch(). Therefore, there is no need of including their declaration (which is implicitly defined in the definition).

like image 26
Claudio Avatar answered Oct 20 '22 19:10

Claudio