Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static variable link error [duplicate]

I'm writing C++ code on a mac. Why do I get this error when compiling?:

Undefined symbols for architecture i386: "Log::theString", referenced from: Log::method(std::string) in libTest.a(Log.o) ld: symbol(s) not found for architecture i386 clang: error: linker command failed with exit code 1 (use -v to see invocation)

Not sure if my code is wrong or I have to add additional flags to Xcode. My current XCode configurations are the default ones for a 'static library' project.

My code:

Log.h------------

#include <iostream> #include <string>  using namespace std;  class Log{ public:     static void method(string arg); private:     static string theString ; }; 

Log.cpp ----

#include "Log.h" #include <ostream>  void Log::method(string arg){     theString = "hola";     cout   << theString << endl;  } 

I'm calling the 'method' from a test code, in this way: 'Log::method("asd"):'

thanks for your help.

like image 818
subzero Avatar asked Feb 14 '12 18:02

subzero


People also ask

Can static variable be initialized twice?

@heksesang: Yes, it happens only in this constellation. If I make both A and B static libs or both shared libs, I do not face the issue (c'tor of A is run only once). However, I would expect the linker to recognize and eliminate duplicate symbols and init calls.

Can we redefine static variable?

Actually static variables can get reassigned. But can't be redefined. Once a static variable defined it can't get redefined throughout the life time of program. But we can change the value.


2 Answers

You must define the statics in the cpp file.

Log.cpp

#include "Log.h" #include <ostream>  string Log::theString;  // <---- define static here  void Log::method(string arg){     theString = "hola";     cout   << theString << endl;  } 

You should also remove using namespace std; from the header. Get into the habit while you still can. This will pollute the global namespace with std wherever you include the header.

like image 174
Luchian Grigore Avatar answered Oct 07 '22 09:10

Luchian Grigore


You declared static string theString;, but haven't defined it.

Include

string Log::theString; 

to your cpp file

like image 41
Lol4t0 Avatar answered Oct 07 '22 10:10

Lol4t0