gcc and libs

Question about which tools to use, bugs, the best way to implement a function, etc should go here. Don't forget to see if your question is answered in the wiki first! When in doubt post here.
Post Reply
Khrista

gcc and libs

Post by Khrista »

Hello!

I have a problem wen try to compile my os. I wrote it on diferents .c files, and i create .h file to include as libs.

In my .h files I put:

#ifndef __NAME_H__
#define __NAME_H__

.
.
.

#endif

but when compile I get that very multiples definitions error. I have some vairables and array ( for control ) in some .h files. Could it be this?

I don't know how can i solve it, can anyone help me??

Thanks.
amirsadig

Re:gcc and libs

Post by amirsadig »

I have had also those error before.
Don't declare any global variable in header files, instead declare it in an C file and then you could declare it in any header file, but as extern. don't ask me why ;D ? because I don't know. :-[

examble :
foo.c

char *foo;

foo.h
extern char *foo
Khrista

Re:gcc and libs

Post by Khrista »

Ok,

thanks for all.
Schol-R-LEA

Re:gcc and libs

Post by Schol-R-LEA »

The explanation of this is fairly simple, actually, if you understand how the preprocessor directives - specifically, the [tt]#include[/tt] directive - work. Unlike the [tt]import[/tt] statement in Java, or the [tt]use[/tt] statement in many Pascal dialects, the #[tt]include[/tt] statement is not a linker instruction. Rather, it is a general-purpose text inclusion - it takes whatever file it is given, and inserts it directly into the compiler's input stream, at the point where the directive occurs. So, if foo.c is

Code: Select all

/* foo.c */

#include "foo.h"

void foo()
{
   HELLO(sucker);
}
and foo.h is,

Code: Select all

/* foo.h */

#define HELLO(x) printf("%s", x)

void foo(void);

char sucker[] = "I am declared in every file that includes foo.h";
then what is actually in the compiler stream after the preprocessor is done with it is,

Code: Select all

void foo(void);

char sucker[] = "I am declared in every file that includes foo.h";

void foo()
{
   printf("%s", sucker);
}
The problem you are having then comes in (so to speak) when another file uses foo.h for the [tt]foo()[/tt] prototype:

Code: Select all

/* bar.c */
#include "foo.h"

void main()
{
   HELLO("World");
   foo();
}
After preprocessing, this would become:

Code: Select all

void foo(void);

char sucker[] = "I am declared in every file that includes foo.h";


void main()
{
   printf("%s", "World");
   foo();
}
As you can see, the global variable [tt]sucker[/tt] is getting siliently redefined in bar.c, even though it is not even explicitly used in that program. This is one of the most common problems found in using header files, so don't feel bad about it.

For an extended discussion on the C preprocessor, see reply #13 in this thread.
Post Reply