【问题标题】:C++ undefined reference (static member) [duplicate]C ++未定义引用(静态成员)[重复]
【发布时间】:2012-11-13 00:21:07
【问题描述】:

可能重复:
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();
}

编译时出现这个错误:

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'

【问题讨论】:

标签: c++ mutex static-methods static-members


【解决方案1】:

当您在 C++ 中的类声明中使用静态成员时,您还需要在源文件中定义它,因此您需要添加 logger.cpp:

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

为什么会这样? 这是因为在 C++ 中,与 C 类似,您必须“告诉”编译器将实际变量放在哪个编译单元中。头文件中的声明只是一个声明(与函数声明相同)。 另请注意,如果将实际变量放在头文件中,则会得到不同的链接错误。 (因为该变量的多个副本将被放置在包括该头文件在内的任何编译单元中)

【讨论】:

    【解决方案2】:

    需要定义静态成员,包括变量。所以在你的 cpp 文件的某个地方,添加这个:

    Mutex Logger::mutex;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-17
      • 1970-01-01
      • 1970-01-01
      • 2021-12-13
      相关资源
      最近更新 更多