G Patel wrote:
Hello,
If a program has two source files: main.c secondaryfunctions.c
and I have a header file: secondaryfunctions.h (with prototypes for the
function)
The only function in main.c is main() and it requires certain headers
(because it uses certain library functions). I added the headers
associated with the library functions at the top of main.c and I added
my custom header file for the secondary function.
The functions in secondaryfunctions.c also require the same library
functions as does main. Do I need to include the same headers in
secondaryfunctions.c? I have not done this because I figure when the
linker adds secondaryfunctions.c to the main program, the headers
within main.c will provide the prototypes to everything. My program
works as expected, but I'm not sure if it was an accident or whether my
line of thinking is accurate. So which is it?
Big thanks in advance :)
Think in terms of modules. I will call your secondaryfunctions
thing the "sf" module for the duration of this reply.
Your sf module comprises two parts - the interface, and the
implementation.
The interface is in sf.h, and the implementation in (at the very least)
sf.c. The sf.h file should include all the interface information needed
by the compiler so that it can compile any source that needs to use
stuff from sf.c. It should also (#!)include any headers that it needs
for the compiler not to complain about it. One good way to achieve
this is to make #include "sf.h" the first line of sf.c, and then
compile. If the compiler moans about anything in sf.h, fix that
by including the necessary standard library header in sf.h, e.g.
#ifndef SF_H
#define SF_H 1
#include <stddef.h>
struct sf
{
int *p;
size_t size; /* this is why you need stddef.h */
};
/* etc */
#endif
Once your compiler's nag list is devoid of refs to sf.h, then
put any remaining #includes (that you need for shutting up the
compiler with regard to sf.c itself) below #include "sf.h"
sf.h is now "idempotent", which means you can stick it anywhere
in the list of includes in main.c.
Now do the same thing with main.c - i.e. add any further #includes
you need for that source.
That's how I do it, anyway (more or less), and it works for me.