对静态方法的未定义引用

Undefined reference to a static method

本文关键字:引用 未定义 静态方法      更新时间:2023-10-16

我正在尝试编译此代码,链接失败,出现以下错误:这就是我编译它的方式;

g++ logtester.cc -I/home/foo/include -L/home/foo/lib -llog4cxx

/tmp/ccADKreY.o(.text+0x120): In function `main': undefined reference to `FrameworkLogger::getInstance()'
collect2: ld returned 1 exit status    

为什么?我该怎么修理它?

#include <log4cxx/logger.h>
#include <log4cxx/xml/domconfigurator.h>
using namespace log4cxx;
using namespace log4cxx::xml;
using namespace log4cxx::helpers;
class FrameworkLogger
{
    private:
        FrameworkLogger();
        LoggerPtr logger;
    public: 
        static LoggerPtr getInstance();
};

(另一个文件:)
#include "FrameworkLogger.h"
#include <iostream>
LoggerPtr FrameworkLogger::getInstance()
{
    std::cout<<"test";
}

(又一个文件:)

#include "FrameworkLogger.h"
#include <iostream>
using namespace std;
int main(){
//      LoggerPtr logger =
        FrameworkLogger::getInstance();
        std::cout<<"test";
}

这听起来像是链接器错误。确保您正确地链接了所有的目标文件

您需要列出所有编译单元(在编译器调用中:

 g++ logtester.cc the-file-you-have-not-named.cc -I/home/foo/include -L/home/foo/lib -llog4cxx