Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple definition for static member?

Tags:

c++

Failed to link up following two files, when I remove the "static" keyword, then it is okay. Tested with g++. Check with readelf for the object file, the static member seems is exported as a global object symbol... I think it should be a local object ...?

static1.cpp

class StaticClass
{
public:

    void    setMemberA(int m)   { a = m;    }   
    int     getMemberA() const  { return a; }

private:
    static  int     a;  

};
int StaticClass::a = 0;
void first()
{
    StaticClass statc1;
    static1.setMemberA(2);
}

static2.cpp

class StaticClass
{
public:

    void    setMemberA(int m)   { a = m;    }   
    int     getMemberA() const  { return a; }

private:
    static  int     a;  

};
int StaticClass::a = 0;
void second()
{
    StaticClass statc1;
    static1.setMemberA(2);
}

With error info:

/tmp/ccIdHsDm.o:(.bss+0x0): multiple definition of `StaticClass::a'

like image 907
Sam Liao Avatar asked Aug 25 '09 06:08

Sam Liao


2 Answers

It seems like you're trying to have local classes in each source file, with the same name. In C++ you can encapsulate local classes in an anonymous namespace:

namespace {
class StaticClass
{
public:

    void    setMemberA(int m)   { a = m;    }   
    int     getMemberA() const  { return a; }

private:
    static  int     a;  

};
int StaticClass::a = 0;
} // close namespace

void first()
{
    StaticClass statc1;
    static1.setMemberA(2);
}
like image 54
Ropez Avatar answered Nov 02 '22 00:11

Ropez


The following is a definition of the static data member. It has to occur only in one file that's compiled and then linked.

int StaticClass::a = 0;

If you have multiple such definitions, it is as if you had multiple functions called first. They will clash and the linker will complain.

I think you are mistaking static members with static applied to namespace scope variables. At the namespace level, static gives the variable or reference internal linkage. But at the class scope level (when applied to a member), it will become a static member - one that is bound to the class instead of each object separately. That then has nothing to do with the C meaning of "static" anymore.

like image 37
Johannes Schaub - litb Avatar answered Nov 02 '22 00:11

Johannes Schaub - litb