gpt4 book ai didi

c++ - 对类方法的 undefined reference

转载 作者:太空狗 更新时间:2023-10-29 23:13:04 24 4
gpt4 key购买 nike

我有一个测试应用程序和静态库。问题未定义对类 Log 方法的引用,但我在代码中找不到错误。

编译日志:

g++ -c -O0 -std=c++14 -Wall -I ../SDL_DekaLib/include main.cpp -o main.o
g++ -c -O0 -std=c++14 -Wall -I ../SDL_DekaLib/include log.cpp -o log.o
ar rc libDeka.a log.o
g++ -O0 -std=c++14 -Wall -I ../SDL_DekaLib/include -L . -lDeka main.o -o test.exe
main.o:main.cpp:(.text+0x10): undefined reference to `Log::Get()'
main.o:main.cpp:(.text+0x28): undefined reference to `Log::Print(char const*, ...)'
main.o:main.cpp:(.text+0x2d): undefined reference to `Log::Get()'
main.o:main.cpp:(.text+0x3a): undefined reference to `Log::~Log()'
collect2.exe: error: ld returned 1 exit status

生成文件

CC=g++
LINK=g++

LIBARIES=-lDeka

CFLAGS= -c -O0 -std=c++14 -Wall -I ../SDL_DekaLib/include
LINKFLAGS= -O0 -std=c++14 -Wall -I ../SDL_DekaLib/include -L . $(LIBARIES)

all: main.o libDeka.a
$(LINK) $(LINKFLAGS) main.o -o test.exe

main.o: main.cpp
$(CC) $(CFLAGS) main.cpp -o main.o

libDeka.a: log.o
ar rc libDeka.a log.o

log.o: log.cpp
$(CC) $(CFLAGS) log.cpp -o log.o

clean:
del *.o
del *.exe
del *.a

日志.h

#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <clocale>
#include <cstdarg>

class Log
{
public:
Log();
~Log();

static Log* Get();
void Print(const char* message, ...);
void Debug(const char* message, ...);
void Error(const char* message, ...);
private:
static Log* _instance;
FILE* _file;

void _print(const char* lvltext, const char* message);
void _init();
void _close();
};

log.cpp - 没有实现

#include "log.h"

Log* Log::_instance = nullptr;

void Log::_init()
{
...
}
void Log::_close()
{
...
}
Log::Log() : _file(nullptr)
{
_init();
}
Log::~Log()
{
_close();
_instance = nullptr;
}
Log* Log::Get()
{
if(!Log::_instance)
Log::_instance = new Log();

return Log::_instance;
}
void Log::Print(const char* message, ...)
{
...
}
void Log::Debug(const char* message, ...)
{
#ifdef DEBUG

...

#endif // DEBUG
}
void Log::Error(const char* message, ...)
{
...
}

void Log::_print(const char* lvltext, const char* message)
{
...
}

主要.cpp

#include "log.h"


int main(int argc, char* argv[])
{
Log::Get()->Print("Test %d", 50);

delete Log::Get();
return 0;
}

以防万一此处所有文件link

最佳答案

来自 https://gcc.gnu.org/onlinedocs/gcc/Link-Options.html

-l library ... It makes a difference where in the command you write this option; the linker searches and processes libraries and object files in the order they are specified. Thus, ‘foo.o -lz bar.o’ searches library ‘z’ after file foo.o but before bar.o. If bar.o refers to functions in ‘z’, those functions may not be loaded.

意味着你需要将main.o放在-lDeka之前。更改链接指令中的顺序:

$(LINK) $(LINKFLAGS) main.o -o test.exe

更改它,使 main.o 出现在 -lDeka 之前。

关于c++ - 对类方法的 undefined reference ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41790045/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com