C++ undefined reference (static member)

c++, mutex, static-members, static-methods

Solution

When you use a static member in a class declaration in C++ you also need to define it in a source file, so in your case you need to add in `logger.cpp`:

Mutex Logger::mutex; // explicit intiialization might be needed

Why is that? This is because in C++, similarly to C you must "tell" the compiler in which compilation unit to put the actual variable. The declaration in the header file is only a declaration (the same way a function declaration is). Also note that if you put the actual variable in the header file, you will get a different linking error. (Since several copies of this variable will be placed in any compilation unit including that header file)

Problem

Possible Duplicate: C++: undefined reference to static class member Logger.h: ``` class Logger { private: Logger(); static void log(const string& tag, const string& msg, int level); static Mutex mutex; public: static void fatal(const string&, const string&); static void error(const string&, const string&); static void warn(const string&, const string&); static void debug(const string&, const string&); static void info(const string&, const string&); }; ``` Logger.cpp: ``` #include "Logger.h" #include <sstream> ofstream Logger::archivoLog; void Logger::warn(const string& tag, const string& msg){ Logger::mutex.lock(); log(tag, msg, LOG_WARN); Logger::mutex.unlock(); } ``` When compiling, I get this error: ``` other/Logger.o: In function `Logger::warn(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)': Logger.cpp:(.text+0x9): undefined reference to `Logger::mutex' Logger.cpp:(.text+0x3b): undefined reference to `Logger::mutex' ```

Original source

Related problems