This topic is now archived and is closed to further replies.

Is this a problem of inclusion protection? I'm Not Sure!

This topic is 5311 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Okay, I''m working hard right now, but there''s a problem that I need help with ASAP. It''s very simple and I''ve had it before, but I''ve never been able to figure it out. Okay, say I have three files: main.c, foo.h, and foo.c. Here''s main.c:
#include "foo.h"

int main( int argc, char** argv )
{ return 0; } /* ignore how bad this looks */
Here''s foo.h:
#ifndef FOO_H
#define FOO_H

int global1, global2, global3;

foo.c can basically hold anything, so I''ll ignore that and move on. To compile this program, foo.c and main.c would first be compiled into respective object files and then linked together. When I do this, I get an error saying that global1, global2, and global3 are being defined multiple times. What''s wrong? I have the inclusion protection? Is it right? I''m not sure. Can you help me out?

Share this post

Link to post
Share on other sites
Basic rule: declarations (ie. prototypes, defines, etc.) go in .h files, definitions (ie. things that the compiler generates code or memory space for) go in .c/.cpp files.

"int global1, global2, global3;" generates space for three ints, and the inclusion protection doesn''t affect this. You need to put that line in your foo.c file, and in your foo.h file put:

extern int global1, global2, global3;

That way, everything that includes foo.h is told that there are already 3 globals, instead of trying to create them each time something includes foo.h.

Share this post

Link to post
Share on other sites
You have to think that #instructions are "preprocessor" instructions. Before the compiler compiles the code the preprocessor does its work.

In the case of the #include instruction you can think it simply subst the line with the include by the "real file". (well, it's a bit more complex but this is a good aproximation)

So you would finish before compile time with line
int global1, ...;
both in main.c and in foo.c that will cause the error.

The guards only protect you for include the same header several times in the same code file.
* you have header A
* Also, you have header B and header C, both of them including header A
* you have header D, that include header B and C.
if you don't have guards, when you try to include header D in a code file you will have the header A twice after the preprocessor replaces the include instructions.

[edited by - Pepe on May 27, 2003 2:00:05 PM]

Share this post

Link to post
Share on other sites