Question

(i have edited my original question to make it more understandable)

here is the prototype for the problem ....

//Txn.h ---this has a static variable, usable by the pgms including it.

class Txn
{
public:
static int i;
static void incr_int();
};
Txn::i=0;

//Txn.cpp

void Txn::incr_int() {i++;}

->produce LibTxn.so
//class1.cpp -> one of the pgm using the static var from Txn.h

#include Txn.h
Txn::incr_int()

-> produce class1.o, with LibTxn.so.
// class2.cpp ->another pgm using the static var from Txn.h

#include Txn.h
cout<<"Txn::i;

-> produce class2.o, by including LibTxn.so
-> .produce class3 (an exe) by using class1.o,class2.o. Since, both class1 and 2 has the statement "Txn::i=0" from "Txn.h", multiple declaration issue happens.
-> .If I remove the statement "Txn::i=0" from Txn.h, then "undefined reference" error appears.
-> .At high lvl, this problem is a kind of having a session variable, which should be assessible from any func in a exe. Those func can be in any obj files used to form the exe. I am fine for any sol, even without static. But I can't change the creation of different .o files (which are using this session var) and combining the .o to produce the exe.

Was it helpful?

Solution 2

I tried to recreate the problem as you described, but it compiled just fine on my computer, and it is difficult to go further without seeing your code.

In the code below, the header tells (declares) every .cpp file that includes it about Foo::x, but Foo::x lives in (is defined in) Foo.cpp (and Foo.o)

foo.h:

class Foo {
public:
    static int x;
};

Foo.cpp:

#include "foo.h"

int Foo::x;

main.cpp:

#include <iostream>
#include "foo.h"

int main(int argc, char *argv[]) {
    Foo::x = 42;
    std::cout << "Foo::x is " << Foo::x; 
}

OTHER TIPS

It is hard to figure out exactly what the problem is if you cannot provide the real code, or at least an example which has the same problem as the real code.

However, most likely the root cause of the problem is that you are not only declaring, but also defining your class's static variable in the header file that contains the class definition.

This means that all the translation units (i.e. .cpp files) which include that header will contain a definition for the static variable, and when merging all the corresponding object files, the linker will eventually complain about that symbol being defined multiple times.

If this is the case, what you should do is to take the initialization of the static variable out of the header file which contains your class's definition and put it in one (and only one) .cpp file.

Yes. it worked by defining the static variable in .cpp. Special thanks to Andy Prowl and iWerner.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top