我创建了一个带有一些方法和变量的类日志,并将其添加到头文件中,但无论我做什么链接器都可以找到我的类
我得到的错误:
C:/msys64/ucrt64/bin/../lib/gcc/x86_64-w64-mingw32/13.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: main.o:main.cpp:(.text+0x1d): undefined reference to `Log::setLevel(int)'
C:/msys64/ucrt64/bin/../lib/gcc/x86_64-w64-mingw32/13.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: main.o:main.cpp:(.text+0x30): undefined reference to `Log::info(char const*)'
collect2.exe: error: ld returned 1 exit status
这是我的main.cpp
#include <iostream>
#include "ep.h"
class Log;
int main()
{
start();
Log log;
log.setLevel(log.logLevlInfo);
log.info("infoooooooooo");
end();
}
这是我的ep.cpp
#include <iostream>
class Log
{
private:
int m_logLevel;
public:
int logLevlInfo = 2;
int logLevlWarn = 1;
int logLevlError = 0;
public:
void setLevel(int level)
{
m_logLevel = level;
}
void warn(const char* message)
{
if(m_logLevel <= 1)
{
std::cout << "warning -> " << message << std::endl;
}
}
void error(const char* message)
{
if(m_logLevel <= 0)
{
std::cout << "error -> " << message << std::endl;
}
}
void info(const char* message)
{
if(m_logLevel <= 2)
{
std::cout << "info -> " << message << std::endl;
}
}
};
void log(const char* st)
{
std::cout << st << std::endl;
}
void end()
{
std::cout << "press any button to exit";
std::cin.get();
}
void start()
{
system("cls");
}
最后是我的ep.h
void end();
void start();
class Log
{
private:
int m_logLevel;
public:
int logLevlInfo;
int logLevlWarn;
int logLevlError;
public:
void setLevel(int level);
void warn(const char* message);
void error(const char* message);
void info(const char* message);
};
这就是我编译的方式
g++ *.cpp
我是初学者,我不知道为什么会发生这种情况......
我尝试了
g++ *.cpp
和g++ -c *.cpp
+g++ *.o
没有任何效果
问题: 您遇到的问题与链接器无法找到 main.cpp 文件中使用的 Log 类函数的定义有关。发生这种情况是因为您已在 main.cpp 和 ep.cpp 中声明了 Log 类,但缺少 Log 类函数的定义。要解决这个问题,您应该在单独的 .cpp 文件中定义 Log 类及其成员函数,然后将所有 .cpp 文件一起编译
解决方案: main.cpp 变为:
#include <iostream>
#include "ep.h"
int main() {
start();
Log log;
log.setLevel(Log::logLevlInfo);
log.info("infoooooooooo");
end();
}
除此之外,建议将类函数声明和定义分开 所以你得到了 ep.h 和 ep.cpp(你已经有了,但不正确)
void end();
void start();
class Log {
private:
int m_logLevel;
public:
static int logLevlInfo;
static int logLevlWarn;
static int logLevlError;
void setLevel(int level);
void warn(const char* message);
void error(const char* message);
void info(const char* message);
};
ep.cpp
#include "ep.h"
int Log::logLevlInfo = 2;
int Log::logLevlWarn = 1;
int Log::logLevlError = 0;
void Log::setLevel(int level) {
m_logLevel = level;
}
void Log::warn(const char* message) {
if (m_logLevel <= 1) {
std::cout << "warning -> " << message << std::endl;
}
}
void Log::error(const char* message) {
if (m_logLevel <= 0) {
std::cout << "error -> " << message << std::endl;
}
}
void Log::info(const char* message) {
if (m_logLevel <= 2) {
std::cout << "info -> " << message << std::endl;
}
}