static variable link error

41,168

Solution 1

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.

Solution 2

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

Include

string Log::theString;

to your cpp file

Share:
41,168

Related videos on Youtube

subzero
Author by

subzero

software developer

Updated on September 08, 2020

Comments

  • subzero
    subzero over 3 years

    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.

  • Vyktor
    Vyktor over 12 years
    Rather initializes instead of defines, no (just asking)?
  • btown
    btown over 12 years
    Perhaps even a better term would be that it allocates space for the string.
  • JavaRunner
    JavaRunner about 10 years
    Thank you so much. You are helped me a lot!
  • Benjineer
    Benjineer over 9 years
    Good point about using namespace *; in the header. It's easier if you shake the habit earlier on.
  • Pellet
    Pellet about 8 years
    Just put using namespace std; inside your own namespace declaration :P namespace your_custom_namespace { using namespace std; }