c++ - Error in including a Global Vector when used in multiple files -
// main.cpp #include <iostream> #include "common.h" #include "second.cpp" #include <vector> int main(){ global = 10; ip.push_back("testtest"); std::cout << global << std::endl; testclass t; t.print(); } //common.h #ifndef global_h #define global_h #include <vector> #include <string> extern int global; extern std::vector<std::string> ip ; #endif // second.cpp #include <iostream> #include "common.h" int global; class testclass{ public: void print();}; void testclass::print(){ global++; std::cout << "global: "<<global << std::endl; std::cout << "ip string: "<<ip[0] << std::endl; } // console error ubuntu:deleteme$ g++ main.cpp /tmp/ccojpyrl.o: in function `testclass::print()': main.cpp:(.text+0x55): undefined reference `ip' /tmp/ccojpyrl.o: in function `main': main.cpp:(.text+0xdd): undefined reference `ip' collect2: error: ld returned 1 exit status
the above works when using int global
variable. when added vector ip
common.h
getting showed error.
this seems elemental thing couldn't answer.
thanks in advance :)
you didn't define std::vector<std::string>
. extern declard it's global defined in place. should add definition under int global
in second.cpp
// second.cpp #include <iostream> #include "common.h" int global; std::vector<std::string> ip; class testclass{
as aside, shouldn't use globals.
Comments
Post a Comment