ivan
ivan

Reputation: 6312

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?

Upvotes: 4

Views: 4174

Answers (5)

Achyuta Aich
Achyuta Aich

Reputation: 581

The header files with a .h extension only includes the declarations of the functions. Its actual implementation is mentioned in a separate .c file. It is the .h file that further includes the .c file which is present in the .h file's local directory . Things will be even clearer if you try to do a project on compilers where you create your own header files

Upvotes: 0

Gopi
Gopi

Reputation: 19864

why we include a header file, which contains declarations but no definitions.

Let's say we have a file

header.h

extern void func();

And this function is defined in some file f1.c and will be called by f2.c then include the required header to notify the compiler that the function definition exists in some other file without including the header the compiler will not know what the call to func() is within main()

f1.c

void func()
{
}

f2.c

#include "header.h"
int main()
{
  func();
}

There can be multiple declarations but there can't be multiple definitions for the same function

Upvotes: 1

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53007

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.

Upvotes: 7

ForceBru
ForceBru

Reputation: 44830

Some people developing libraries do not want to let everyone know full code. They make it a library and then create the headers so everyone could use it. Moreover, @iharob's right, if we include definitions in headers, it's gonna make lots of troubles with code.

Upvotes: 0

user1627167
user1627167

Reputation: 339

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

Upvotes: 2

Related Questions