July 18th, 2013, 04:01 AM
Header included twice - why?
Hi, I'm trying to grasp GCC and C properly, I never really learned them well the first time around. On this page of a web-book on GCC, the header file hello.h is included TWICE - once in the main.c, the other time in hello_fn.c. Why so? I'd figure there's no need to include it (hello.h) in hello_fn.c, since the function that hello.h prototypes is already gonna get defined in hello_fn.c!
July 18th, 2013, 10:24 AM
Each source file (.c) is compiled separately and independently of all other source files.
Every source file that needs information that's in hello.h must #include that header file.
If you were to not #include it in one of those source files, then that source file would not compile (NOTE: getting warnings means that the source file failed to compile successfully).
If you still do not understand, then please point out which part of that you don't understand.
July 19th, 2013, 12:38 AM
My problem is with the hello_fn.c file, because it contains the definition of the hello function. So why would it ever need to include the prototype (which is like a partial definition) via hello.h?
Originally Posted by dwise1_aol
July 19th, 2013, 01:19 AM
> So why would it ever need to include the prototype (which is like a partial definition) via hello.h?
Well if you change one of them, the other will almost certainly break at compile time.
Which is a lot better than having all manner of weird failures at run-time.
July 19th, 2013, 02:37 AM
Well, that would all depend on exactly how you had written your hello_fn.c source file.
Originally Posted by st_crab
If hello_fn.c contains multiple functions, some of which call the hello function before it is even defined in the source file, then you most certainly would need to have it in the header file and to #include the header file.
But if the hello_fn.c file does not contain functions that also depend on the hello function, then there is of course no need to have #included that function prototype. Though there was also absolutely no harm in having #include'd that function prototype.
No harm, no foul. Ne?
There are far too many picky little details to consider here.
We have this source file, hello_fn.c. It has functions in it that other source files need, so those source files absolutely need to #include the header file that contains that function's prototype. OK, that is a given.
Now we have hello_fn.c itself. Does it really need to know what's in the header file? Only if any function within it tries to reference one of the functions in the header file.
OK, so let's assume that's not the situation. What harm does it do to prototype a function that nobody references before it's defined? None whatsoever.
So just what do you think is the problem?
Comments on this post