views:

96

answers:

3

Hi Everyone,

I am doing a project in C and I have a problem with building it. It is:

I have two separate sub systems[A and B] in my project that use the functionality of yet another sub system[C]. To do this, they #include the header files necessary. The obligation is that both the sub systems[A and B] have to be built separately, by which I mean that I have two separate 'Makefile's for the subsystems and I run 'make' on each separately.

Now, when I try to unite all my subsystems[A,B,C] into one single project, gcc tells that some functions are already declared and these functions belong to subsystem C.

I realize that header files are included at compile time, i.e., when I use 'make' on the sub systems[A and B]. So, when I am trying to unite all of them, they are actually being double declared.

Can someone help me with a solution to this? Any solution, that does not require me to compile both the sub systems[A and B] together will be good.

A: 

You can use #ifndef .. to avoid double inclusion of header file

#ifndef <some name identifying the header file>
#define <some name identifying the header file>
//
//

// header file content will go here 

//

// 
#endif
Xinus
only affects single compilation units
anon
Also note that // is not a valid C comment.
Aif
A: 

Does you C-header file include only the declaration or also the implementation?

If it contains implementation, then you should take it out and compile it separately.

Tristram Gräbener
+3  A: 

Well this is either a compile error or a linker error.

If it's a compile-time error, you need to use some include guards in your .h files like this:

#ifndef FILE_NAME_H
#define FILE_NAME_H

// file contents here

#endif

This will stop a file being included more than once. Change FILE_NAME_H to reflect the file name so each include guard is unique.

If it's a link-time error, this usually happens when you have function bodies (i.e. the {}) in the header files. Because multiple files will include the header, each will have its own definition in the object code which will cause the linker conflict.

The best way to get around this is to simply make sure all function bodies go in the .c files. You can try and __inline__ them if they are short enough, but the compiler isn't guaranteed to listen to you.

Mike Weller