Why am I getting a duplicate symbol when declaring this public member function in another file? (C++)
Alright, so I've been setting up a pretty simple class in C++ to handle changing the functions I want to use with GLUT. But, I am having trouble when defining one of the public member functions in the .cpp file that corresponds to the header file containing the class definition.
When I define the class in the header file, I don't get any compilation errors. But when I define the function in the .cpp file, with the header file included, I get an error "duplicate symbol SystemModule::setupGlutFunctions
". As far as I can tell, I'm using the correct syntax for defining this function in a separate file than the original. Here is the code:
#include "system.h"
void SystemModule::setupGlutFunctions()
{
glutDisplayFunc(displayFunc);
glutReshapeFunc(reshapeFunc);
glutMouseFunc(mouseFunc);
glutKeyboardFunc(keyboardFunc);
glutSpecialFunc(specialFunc);
glutIdleFunc(idleFunc);
glutMotionFunc(motionFunc);
glutPassiveMotionFunc(passiveMotionFunc);
return;
}
The actual contents of the code don't really matter, as that compiles fine when declared in the .h file, inside the class definition. But when I try to define the function in a separate .cpp file, I get the error. It's a public function.
I am using Xcode on Mac OS X 10.5. Has anyone else gotten this error before? And can anyone tell me if I'm doing something wrong in the syntax or if I have to do something special in Xcode for this to work?
Much obliged开发者_如何学编程, E.
This looks like a linker error, not a compiler error, which suggests that somehow you're compiling two different copies of the setupGlutFunctions
code and trying to link them together. This could either be because you have two different files with the same implementation that are being linked together.
One possible candidate - are you #include
-ing the .cpp file at the end of the .h file? If so, any file that #include
s your header file will get their own copy of the setupGlutFunctions
implementation. At link time, the linker will see that the function has multiple different definitions, and will raise an error because it's not sure which one of the many identical implementations you were looking for.
Another possible candidate (mentioned above by @DougT) - if you accidentally provided an implementation in the header, like this:
class SystemModule {
public:
void setupGlutFunctions() {
/* ... */
}
};
Then you have actually defined two implementations of the function - one in the header and one in the .cpp file. Changing this to read
class SystemModule {
public:
void setupGlutFunctions();
};
could fix this.
精彩评论