0

The following code compiles fine. but when goes to linking,

it shows following error

Undefined symbols for architecture x86_64:
    "derived::counter", referenced from:
     derived::getAddressCounter()      in main.cpp.o 
     ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status

I suspect there is something wrong with the static. but not sure why. Because once I take out the static, the code links fine. But how does static plays any role in this code?

#include <iostream>
#include <string>

struct base_result { };
struct result : public base_result {
    int a;
    std::string b;
};


struct base {
    static base_result counter;

};

struct derived: public base {
    static result counter;

    result * getAddressCounter(){
        counter.a = 10; 
        counter.b = "haha";
        return &counter;
    }   
 };

int main (){ 
    derived d;
    result * ptr;

    ptr = d.getAddressCounter();

    ptr->a = 20; 
    ptr->b = "baba";
    std::cout << ptr->a << std::endl;

    std::cout << ptr->b << std::endl;
    return 0;
}
Negative Zero
  • 1,224
  • 3
  • 10
  • 19

2 Answers2

3
struct base 
{ 
     static base_result counter; 
}; 

Only declares the static member, You also need to define it once in your cpp file.

Good Read: What is the difference between a definition and a declaration?

Community
  • 1
  • 1
Alok Save
  • 202,538
  • 53
  • 430
  • 533
1

In contrast to member variables which get a reserved space in every created object, static variables can't just be declared, they need to be implemented/defined too.

Just add the lines

base_result base::counter;
result derived::counter;

to your code and it will compile just fine. Those lines instructs the compiler to actually reserve space to store the static variables you declared earlier.

Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294