Cuthbert
Cuthbert

Reputation: 2998

C++ Static variable and unresolved externals error

I was hoping I could get some clarification on static variables of a class.

For example: I have two different classes which perform completely different functions, alpha and beta. Within alpha, I declare a static variable of type beta so it looks like this:

//alpha.h

#pragma once
#include <iostream>
#include "beta.h"

class alpha{
public: 
    alpha(){

    }

    static beta var; 

    void func(){
        var.setX(3);
    }

    void output(){

    }
};

//beta.h

#pragma once
#include <iostream>
using namespace std; 

class beta{

public: 

    int x; 
    char y; 

    beta(){
        x = 0; 
        y = ' '; 
    }

    void setX(int _X){
        x = _X; 
    }

};

//main.cpp

#include <iostream>
#include <iomanip>
#include "alpha.h"
using namespace std; 

int main(){
    alpha x, y, z; 
    x.func(); 
}

Now when I try to compile this, I get an unresolved externals error:

error LNK2001: unresolved external symbol "public: static class beta alpha::var" (?var@alpha@@2Vbeta@@A)

I'm not sure what to change or what else I need to add to make something like this work. I want x, y, and z to essentially share the same beta variable. I think I can accomplish this same thing by just passing by reference one beta variable into each of them. But I want to know if it's possible to do this same thing using the static keyword here because static members of a class have the same value in any instance of a class. Unless I have that definition wrong.

Upvotes: 0

Views: 2213

Answers (2)

Vaughn Cato
Vaughn Cato

Reputation: 64298

static variables inside a class must still be defined somewhere, just like methods:

Put this in main.cpp:

beta alpha::var;

Upvotes: 5

Alex F
Alex F

Reputation: 43311

Add this to main.cpp:

beta  alpha::var;

var in h-file is only type declaration. Variable should be created in some source file.

Upvotes: 4

Related Questions