简体   繁体   中英

C++: gcc can't find static member when linking

I get the error:

file.cpp:20: undefined reference to `MyClass::arr'

At this line, I have:

#include "MyClass.hpp"
extern "C" {
void MyClass::func() {
 arr = 0;
}

At header:

class MyClass {
    public:
     static int arr;
     static void func();
}

PS gcc (4.x) is called with: -Xlinker -zmuldefs to avoid multiple definition checking.

This makes no sense :

#include <MyClass.hpp>
extern "C" {
void MyClass::func() {
 arr = 0;
}

write

#include <MyClass.hpp>

int MyClass::arr = 0; // needs to be instantiated to satisfy linker.

void MyClass::func() 
{
  arr = 0;
}

implementation

#include "MyClass.hpp"

 void MyClass::func()
 {
     this->arr = 0;
 }

header file

class MyClass 
{
public:
    static int arr;
    static void func();
}

Static class fields, after being declared in the class statement, must be also defined in a single .cpp file. In such file you should put:

int MyClass::arr;

By the way, the #include statements have <> brackets only when you're including system headers; for your own headers you should use the usual double quotes ( "" ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM