c++ - Using a static variable of a shared library in more than one functions of a same exe, but different object file -
(i have edited original question create more understandable)
here prototype problem ....
//txn.h ---this has static variable, usable 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 -> 1 of pgm using static var txn.h
#include txn.h txn::incr_int()
-> produce class1.o, libtxn.so. // class2.cpp ->another pgm using static var txn.h
#include txn.h cout<<"txn::i;
-> produce class2.o, including libtxn.so -> .produce class3 (an exe) using class1.o,class2.o. since, both class1 , 2 has statement "txn::i=0" "txn.h", multiple declaration issue happens. -> .if remove statement "txn::i=0" txn.h, "undefined reference" error appears. -> .at high lvl, problem kind of having session variable, should assessible func in exe. func can in obj files used form exe. fine sol, without static. can't alter creation of different .o files (which using session var) , combining .o produce exe.
i tried recreate problem described, compiled fine on computer, , hard go farther without seeing code.
in code below, header tells (declares) every .cpp file includes foo::x
, 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 " << foo::x; }
c++ shared-libraries linker-error static-members multiple-definition-error
No comments:
Post a Comment