C ++未定义的引用(静态成员) [英] C++ undefined reference (static member)

查看:105
本文介绍了C ++未定义的引用(静态成员)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
C ++:对静态类成员的未定义引用

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:

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 ++中的类声明中使用静态成员时,还需要在源文件中定义它,因此,在这种情况下,您需要添加logger.cpp:

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

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

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)

这篇关于C ++未定义的引用(静态成员)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆