C++ undefined reference (static member) [duplicate]

时间秒杀一切 提交于 2019-12-14 02:43:24

问题


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'

回答1:


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)




回答2:


Static members, including variables, need to be defined. So somewhere in your cpp file, add this:

Mutex Logger::mutex;


来源:https://stackoverflow.com/questions/13549345/c-undefined-reference-static-member

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!