multiple definition of... (class function)

1
2
3
4
5
6
class aClass {
...
public:
aClass();       // constructor
aClassFun(double aParam);       // public function
};


This class, with its public function, is declared in the header file aClassHeader.h
NO class instances are created here, not even as extern.

Then, at the top of the file module_1.cpp there is:

1
2
3
#include "aClassHeader.h"

class aClass myClass1;  // as global 


Here (in module_1.cpp) I use the public function of myClass1 and everything works fine!


Now, I *MUST* use the same aClass in module_2.cpp, hence at the top of this file I write:

1
2
3
#include "aClassHeader.h"

class aClass myClass2;  // as global 



Doing so I get linker errors:

/tmp/cce2gpMN.o: In function `aClass::aClassFun(double)':
module_2.cpp:(.text+0x1a0): multiple definition of `aClass::aClassFun(double)'
/tmp/cco6b7Gk.o:module_1.cpp:(.text+0x1a0): first defined here

I did google this error but I could not find similar conditions.

I would really appreciate some help. Thanks.
Last edited on
EDIT: nvm :p
Last edited on
That's wrong.
It's like instantiating, perfectly legally: struct aStruct myStruct1;

I see that the problem resides in the double #include "aClassHeader.h"

But that class is in a Header file. How can I use it within different .cpp files?
Last edited on
header guards: http://www.cplusplus.com/forum/articles/10627/
If you want the variable local to that cpp, declare it as static
Or put it in an unnamed namespace.
>> header guards:...
Thanks!

>> Or put it in an unnamed namespace.
Interesting. A few more words or two lines... please...
closed account (DSLq5Di1)
Do you have a seperate file for your class member definitions or is that included in the header also? Assuming this is the problem..

aClassHeader.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class aClass
{
public:
	aClass();
	void aClassFun(double aParam);
};

aClass::aClass()
{
}

void aClass::aClassFun(double aParam)
{
}

module_1.cpp
1
2
#include "aClassHeader.h"
aClass myClass1;


module_2.cpp
1
2
#include "aClassHeader.h"
aClass myClass2;

module_1.cpp & module_2.cpp will be compiled seperately with their own defintions of the constructor and aClassFun(). So when the linker is trying to combine all of your compiled code into one file.. it will come across multiple definitions.

Move your defintions for aClass out of the header and into its own file,

aClassHeader.h
1
2
3
4
5
6
class aClass
{
public:
	aClass();
	void aClassFun(double aParam);
};

aClass.cpp
1
2
3
4
5
6
7
8
9
#include "aClassHeader.h"

aClass::aClass()
{
}

void aClass::aClassFun(double aParam)
{
}
Last edited on
Thanks everyone. The last post and the link to header guards made the stuff working.
Topic archived. No new replies allowed.