3

重複の可能性:
C++: 静的クラス メンバーへの未定義の参照

ロガー.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&);
};

ロガー.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'
4

2 に答える 2

8

C++ のクラス宣言で静的メンバーを使用する場合は、ソース ファイルでも定義する必要があるため、この場合は次のように追加する必要がありますlogger.cpp

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

何故ですか?これは、C++ では、C と同様に、実際の変数を配置するコンパイル ユニットをコンパイラに「伝える」必要があるためです。ヘッダー ファイル内の宣言は、単なる宣言です (関数宣言と同じです)。また、実際の変数をヘッダー ファイルに入れると、別のリンク エラーが発生することにも注意してください。(この変数の複数のコピーが、そのヘッダー ファイルを含む任意のコンパイル ユニットに配置されるため)

于 2012-11-25T08:11:48.147 に答える
3

変数を含む静的メンバーを定義する必要があります。したがって、cpp ファイルのどこかに、これを追加します。

Mutex Logger::mutex;
于 2012-11-25T08:10:49.217 に答える