C++ with Extern “C” causing Duplicate Symbols Error
-
03-07-2021 - |
Question
I am trying to use a extern "C" function inside my header file for a c++ class.
When I compile I keep getting the error
duplicate symbol _currentInstance in:
main.o
GLHandler.o
I thought I had the right guards but can't seem to figure out why this is happening. Any help would be much appreciated.
Here is the header file.
#ifndef GLHANDLER_H
#define GLHANDLER_H
#include "LoadedObject.h"
#ifdef __cplusplus
extern "C" {
void displayCallback();
}
#endif
class GLHandler {
private:
LoadedObject *object;
public:
GLHandler(LoadedObject *);
void initializeVBO(LoadedObject *);
void renderObject(struct model *);
void displayFunction(void);
model *createModel(void);
void setupDisplayCallback();
};
GLHandler *currentInstance;
#ifdef __cplusplus
}
#endif
#endif
EDIT: Quickly pointed out by David, the extern GLHandler *currentInstance fixed the error.
Solution
This problem has nothing to do with the extern "C"
declaration - you're defining a global variable in the header, so it gets defined in each compilation unit:
GLHandler *currentInstance;
In the header, you should instead use:
extern GLHandler *currentInstance;
then in exactly one .cpp file have:
GLHandler *currentInstance;
As a side note, as it stands right now, the header is valid only for C++, since it has a class definition. The #ifdef __cplusplus
directives are pointless clutter (though harmless).