kagali-san
kagali-san

Reputation: 3082

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();
}

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

Upvotes: 0

Views: 1097

Answers (3)

Matteo Italia
Matteo Italia

Reputation: 126937

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 ("").

Upvotes: 1

Cesar A. Rivas
Cesar A. Rivas

Reputation: 1355

implementation

#include "MyClass.hpp"

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

header file

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

Upvotes: 1

AndersK
AndersK

Reputation: 36092

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;
}

Upvotes: 4

Related Questions