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

Started by
3 comments, last by Some Guy 20 years, 10 months ago
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;

#endif
 
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?
Advertisement
Here''s foo.h:

#ifndef FOO_H
#define FOO_H

extern int global1, global2, global3;

#endif


Here''s foo.c:

#include "foo.h"

int global1, global2, global3;
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.
Brianmiserere nostri Domine miserere nostri
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.
Ex:
* 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]
Got it. Thank you, man. I appreciate it.

This topic is closed to new replies.

Advertisement