Declaring class objects in the header file

Welcome all.

I seem to be hooked on the fundamental, but I can't find a solution anywhere. Anywho, continue and explain.

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

I declare a SA class 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 communication error during compilation: LNK2005 error: "class SA Obj1" (? Obj1 @@ 3VSA @@ A), already defined in main.obj

The only object definition is in add.h, not elsewhere. The program compiles just fine if you declare objects in the main, and not in the header:

main.ccp

#include "additional.h" 

int main() {

    SA Obj1;
    Obj1.x = 5;

    ...
}

, add.cpp, main.cpp. ?

+5
3

Obj1 Obj2 .cpp, .h

add.h

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

main.cpp

#include "additional.h" 

SA Obj1, Obj2;

int main() {

 Obj1.x = 5;

 ...
}

Obj1 Obj2 .h , extern .h :

extern SA Obj1, Obj2;

.cpp :

main.cpp

SA Obj1, Obj2;

, , .h, Obj1 Obj2. , .h, Obj1 Obj2. extern, , - ( .cpp ).

+11

extern. extern , cpps.

:

extern SA Obj1; // in header

SA Obj1;// in any one (no more than one) cpp
+6

:

static SA Obj1, Obj2;

1 . , , .h, , , .

+4

All Articles