g++ Undefined reference static member variable

2019-08-03 18:24发布

问题:

I am Compiling this using g++ and a makefile. The g++ version is 4.1.2 20080704.

Here is the simplified code which still contains the error:

#ifdef __cplusplus
extern "C" 
{
#endif

 class MyClass
  {
    public:
    MyClass() {};
    MyClass& operator=(MyClass&);
    static MyClass& instance() { return log; };

    private:
    static MyClass log;

  }; 

//MyClass MyClass::log;

int main()
{
  MyClass& myClass = MyClass::instance();
  return 0;
}

#ifdef __cplusplus
} //extern "C" 
#endif

When I compile with 'g++ MyClass.cpp" I get this error: 'In Function MyClass::Instance()' : MyClass.cpp : 'Undefined reference to MyClass::log

If I compile with 'g++ MyClass.cpp -c' It builds the object file, but linking that file causes the same error during linking. I tried defining the static variable with "MyClass MyClass::log;" after the class definition, but since it's compiling it in C, I don't think that will work. It gives an error message "C++ linkage conflicts with new definition with C linkage"

I'm not sure how to solve this, I've been banging my head against this for a few days now. Any help is greatly appreciated.

Extra background info:

The original cpp file this is derived from contains "Simulink-defined functions which must use the C-function syntax." I'd like to make as few changes as possible to the existing code. I'm not a C programmer, so I have limited understanding here. I do know that these functions are being used with simulink and everything compiles inside the matlab compiler. We are trying to export what simulink created so that we can integrate it in another program, but this is one of the many problems we have compiling. Hopefully that gives some better background info

回答1:

The declaration of MyClass::log in the class definition gets C++ linkage despite the extern "C", because static class members simply don't exist in C. But for some reason, the definition of MyClass::log outside the class definition gets C linkage, which doesn't make much sense to me.

But you can get around the problem by removing the definition from the scope of the extern "C". Why are you using extern "C"in a C++ file anyway?