K
Ken Human
I am writing a program that contains multiple source and header files,
generally one of each for classes that are similar to each other. I
want to be able to declare an object of the class declared in a specific
header file, and include that header in the source file of a different
set of classes so that those classes will have access to that object. I
believe I'm going about this in the wrong way, any advice would be
appreciated. A demonstration follows:
/*main.cpp*/
#include "a.h"
#include "b.h"
int main() {
B myB;
return 0;
}
/*a.h*/
#ifndef A_H
#define A_H
class A {
public:
A();
};
A myA;
#endif
/*b.h*/
#ifndef B_H
#define B_H
class B {
public:
B();
};
#endif
/*a.cpp*/
#include "a.h"
A::A() { }
/*b.cpp*/
#include "b.h"
#include "a.h"
B::B() { A newA = A(myA); }
I get link errors when building this project:
..NET 2005:
a.obj : error LNK2005: "class A myA" (?myA@@3VA@@A) already defined in
main.obj
b.obj : error LNK2005: "class A myA" (?myA@@3VA@@A) already defined in
main.obj
Cygwin:
ken@ken-wn0vf73qmks ~/c
$ g++ main.cpp a.cpp b.cpp -o main -Wall
/cygdrive/c/DOCUME~1/ken/LOCALS~1/Temp/ccZtqXQj.o(.bss+0x0):a.cpp:
multiple definition of `_myA'
/cygdrive/c/DOCUME~1/ken/LOCALS~1/Temp/ccSiR2mi.o(.bss+0x0):main.cpp:
first defined here
/cygdrive/c/DOCUME~1/ken/LOCALS~1/Temp/ccKtlZoq.o(.bss+0x0):b.cpp:
multiple definition of `_myA'
/cygdrive/c/DOCUME~1/ken/LOCALS~1/Temp/ccSiR2mi.o(.bss+0x0):main.cpp:
first defined here
collect2: ld returned 1 exit status
generally one of each for classes that are similar to each other. I
want to be able to declare an object of the class declared in a specific
header file, and include that header in the source file of a different
set of classes so that those classes will have access to that object. I
believe I'm going about this in the wrong way, any advice would be
appreciated. A demonstration follows:
/*main.cpp*/
#include "a.h"
#include "b.h"
int main() {
B myB;
return 0;
}
/*a.h*/
#ifndef A_H
#define A_H
class A {
public:
A();
};
A myA;
#endif
/*b.h*/
#ifndef B_H
#define B_H
class B {
public:
B();
};
#endif
/*a.cpp*/
#include "a.h"
A::A() { }
/*b.cpp*/
#include "b.h"
#include "a.h"
B::B() { A newA = A(myA); }
I get link errors when building this project:
..NET 2005:
a.obj : error LNK2005: "class A myA" (?myA@@3VA@@A) already defined in
main.obj
b.obj : error LNK2005: "class A myA" (?myA@@3VA@@A) already defined in
main.obj
Cygwin:
ken@ken-wn0vf73qmks ~/c
$ g++ main.cpp a.cpp b.cpp -o main -Wall
/cygdrive/c/DOCUME~1/ken/LOCALS~1/Temp/ccZtqXQj.o(.bss+0x0):a.cpp:
multiple definition of `_myA'
/cygdrive/c/DOCUME~1/ken/LOCALS~1/Temp/ccSiR2mi.o(.bss+0x0):main.cpp:
first defined here
/cygdrive/c/DOCUME~1/ken/LOCALS~1/Temp/ccKtlZoq.o(.bss+0x0):b.cpp:
multiple definition of `_myA'
/cygdrive/c/DOCUME~1/ken/LOCALS~1/Temp/ccSiR2mi.o(.bss+0x0):main.cpp:
first defined here
collect2: ld returned 1 exit status