Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: Why do we include header files, which declare but don't define?

At a high level, I understand we use #include statements to make code from other files available to the current file. But I don't understand why we include a header file, which contains declarations but no definitions.

Maybe I need to learn more about the compilation/linking process to fully understand the mechanics, but is there a high level concept I'm failing to grasp at the outset?

Edit: All the answers helped clarify my question, which boils down to: once we've notified the compiler that a function is defined elsewhere, how does it figure out where to find that definition?

like image 835
ivan Avatar asked Sep 16 '25 02:09

ivan


2 Answers

Because if you include the header where there are definitions, in different .c files, you will have Multiple Definitions.

The declaration is sufficient, because it allows the compiler to generate the calling code, after that the linker takes care of finding the definition and links the function call to the actual definition.

like image 85
Iharob Al Asimi Avatar answered Sep 17 '25 17:09

Iharob Al Asimi


One reason is you can use pre-compiled libraries as well.

like image 37
user1627167 Avatar answered Sep 17 '25 19:09

user1627167