Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring class objects in a header file

Greetings everyone.

I seem to be snagging on a fundimental but I cant find the solution anywhere. Anywho, will go ahead and explain.

I have a program consisting of three files; main.ccp, add.h, add.cpp.

I declare the class 'SA' in add.h and have all my functions defined in add.cpp

additional.h

class SA {
    ...
public
    int x;
} Obj1, Obj2;

main.ccp

#include "additional.h" 

int main() {

    Obj1.x = 5;

    ...
}

This gives me a link error on compiling: error LNK2005: "class SA Obj1" (?Obj1@@3VSA@@A) already defined in main.obj

The only deffinition of the object occurs in add.h, and no where else. The program compiles just fine if declare the objects in the main and not the header:

main.ccp

#include "additional.h" 

int main() {

    SA Obj1;
    Obj1.x = 5;

    ...
}

The issue is that I want to use the objects primarially within add.cpp, but still need to initialise several public values through main.cpp. Any words of wisdom?

like image 513
Raugnar Avatar asked Mar 11 '09 07:03

Raugnar


1 Answers

Declare Obj1 and Obj2 in your .cpp instead of at .h

add.h

class SA {
 ...
public
    int x;
};

main.cpp

#include "additional.h" 

SA Obj1, Obj2;

int main() {

 Obj1.x = 5;

 ...
}

If you want to declare Obj1 and Obj2 in your .h file, add extern in the .h file like so:

extern SA Obj1, Obj2;

but you should declare the objects in a .cpp file in your project:

main.cpp

SA Obj1, Obj2;

The reason for this is that everytime you include the .h file, you are declaring Obj1 and Obj2. So if you include the .h file two times, you will create two instance of Obj1 and Obj2. By adding the keyword extern, you are telling the compiler that you have already decalred the two variables somewhere in your project (preferably, in a .cpp file).

like image 160
MrValdez Avatar answered Oct 03 '22 00:10

MrValdez