Structure raises linker exception multiple definition of
As I read from some online examples structures should work like this:
Code:
struct nameOfStruct
{
int myMember1;
short myMember2;
};
int main()
{
nameOfStruct myInstance;
myInstance.myMember = 444;
return 1;
}
This code doesn't link good:
Undefined reference to nameOfStruct::myMember1
First question, why?
So i found some example and "repaired" my code:
Code:
struct nameOfStruct
{
int myMember1;
short myMember2;
};
int nameOfStruct::myMember1;
int main()
{
nameOfStruct myInstance;
myInstance.myMember = 444;
return 1;
}
Now code compiles well.
As my application developed, I came to the point when I must make this type (structure) visible to multiple units. So i tried to do this:
Code:
//Structures.h
struct nameOfStruct
{
int myMember1;
short myMember2;
};
int nameOfStruct::myMember1;
Re: Structure raises linker exception multiple definition of
You should post the actual code that you tried. In your first example, you should be getting a compile error, not a linker error, because the struct has no member named myMember.
Compile and link this program:
Code:
struct nameOfStruct
{
int myMember1;
short myMember2;
};
int main()
{
nameOfStruct myInstance;
myInstance.myMember1 = 444;
return 0;
}
C + C++ Compiler: MinGW port of GCC
Build + Version Control System: SCons + Bazaar
Re: Structure raises linker exception multiple definition of
That's a typo i made while typing code to this site. Code is flawless in my actual program and members don't have generic names like myMember1. Still i have:
Re: Structure raises linker exception multiple definition of
Ah, now we're talking
The big difference between this new code snippet and what you posted earlier is that the member variables are static members. Generally, static member variables are declared in the class definition (in a header) and then defined in a source file. This explains the multiple definition errors: you defined them in a header, and then included the header in more than one source file, thus the same static members were defined in more than one translation unit.
C + C++ Compiler: MinGW port of GCC
Build + Version Control System: SCons + Bazaar
Re: Structure raises linker exception multiple definition of
Ok I make them non-static (i made them static while attempting to solve my problem xD and obviously buried my self even deeper), and now when i removed that I compiled my code without any errors. Now i am confused what first error was so i putted that members static. Oh s*it i am so confused... My first week in C++, it's nice language just if you don't do something right you get yourself dizzy. Anyway thanks
Bookmarks