1
votes

I've got a little problem. I have 2 files: one.c and two.c they both decler and implement the struct: StackNode the header files are: one.h:

 #ifndef ONE_H
 #define ONE_H

 typedef struct StackNode StackNode;
 #endif

two.h:

 #ifndef TWO_H
 #define TWO_H

 #include "one.h"

 #endif

cpp files: one.c:

 #include <stdio.h>
 #include <malloc.h>
 #include <string.h>
 #include <stdlib.h>
 #include "one.h"

 struct StackNode
 {
   ........
 };

two.c:

 #include <stdio.h>
 #include <malloc.h>
 #include "two.h"
 struct StackNode
 {
   ........
 };

Why this compile and run in linox but in visual stutio it says: two.obj : error LNK2005: "struct StackNode * top" (?top@@3PAUStackNode@@A) already defined in one.obj 1>c:\users\documents\visual studio 2010\Projects\Exercise\Debug\Exercise.exe : fatal error LNK1169: one or more multiply defined symbols found

What can I do so it will work in visual too? Thank you :)

1
Change the name or put them in different namespaces (or make them the same and only have one definition). - crashmstr
but why/how it's working on linux? - Dvir Samuel
And why are you including malloc.h in c++? - crashmstr
I use alocation later in those files.. That was just an exemple - Dvir Samuel
@user3169750 So what is sizeof(StackNode) in your application? Is it sizeof(StackNode) in one.cpp, or is it sizeof(StackNode) in two.cpp? In short, don't do what you're doing now - -it will lead to weird bugs. What if you called new StackNode in one.cpp, and you passed that pointer to a function defined in two.cpp and two.cpp dereferences that pointer? See the issues? Just define two different structs, or use the very same struct. - PaulMcKenzie

1 Answers

1
votes

The linker does not say that the structure itself is defined twice. It says that object top is defined twice like struct StackNode * top. You have to define it only in one compilation unit.

two.obj : error LNK2005: "struct StackNode * top" (?top@@3PAUStackNode@@A) already defined in one.obj