未定义引用 Class::Function 链接器错误
Undefined reference to Class::Function linker error
尝试从两个 .cpp 文件和一个 .h 文件构建可执行文件,但似乎出现链接器错误。这是我遇到的错误...
/usr/bin/ld: CMakeFiles/Diary.dir/home/adam/Dev/Diary/src/Main.cpp.o:
in function `main': Main.cpp:(.text+0x73): undefined reference to
`Entry::write(char*, char*)' collect2: error: ld returned 1 exit
status make[2]: *** [CMakeFiles/Diary.dir/build.make:85:
/home/adam/Dev/Diary/bin/Diary] Error 1 make[1]: ***
[CMakeFiles/Makefile2:105: CMakeFiles/Diary.dir/all] Error 2 make: ***
[Makefile:84: all] Error 2
这是我的代码...
Main.cpp
#include <iostream>
#include "CSV.hpp"
using namespace std;
int main(int argc, char* argv[]) {
if(argc==1){
cout << "Usage: ./Diary add <date> <text>" << endl;
}
else{
Entry entry;
bool success = entry.write(argv[1], argv[2]);
}
return 0;
}
CSV.cpp
#include <iostream>
#include <fstream>
using namespace std;
class Entry {
private:
public:
bool write (char* date, char* text){
ofstream file;
file.open("../Diary.csv", ios_base::app);
file << date << "," << text << endl;
file.close();
return true;
}
};
CSV.hpp
#pragma once
class Entry{
private:
public:
bool write (char* date, char* text);
};
真的不确定问题出在哪里。有什么建议吗?
您 CSV.cpp 文件应该是这样的:
#include <iostream>
#include <fstream>
#include "CSV.hpp"
using namespace std;
bool Entry::write (char* date, char* text)
{
ofstream file;
file.open("../Diary.csv", ios_base::app);
file << date << "," << text << endl;
file.close();
return true;
}
并且您必须将 cpp
文件(Main.cpp
和 CSV.cpp
)和 link 编译为 target
(您的程序可执行文件。)
尝试从两个 .cpp 文件和一个 .h 文件构建可执行文件,但似乎出现链接器错误。这是我遇到的错误...
/usr/bin/ld: CMakeFiles/Diary.dir/home/adam/Dev/Diary/src/Main.cpp.o:
in function `main': Main.cpp:(.text+0x73): undefined reference to
`Entry::write(char*, char*)' collect2: error: ld returned 1 exit
status make[2]: *** [CMakeFiles/Diary.dir/build.make:85:
/home/adam/Dev/Diary/bin/Diary] Error 1 make[1]: ***
[CMakeFiles/Makefile2:105: CMakeFiles/Diary.dir/all] Error 2 make: ***
[Makefile:84: all] Error 2
这是我的代码...
Main.cpp
#include <iostream>
#include "CSV.hpp"
using namespace std;
int main(int argc, char* argv[]) {
if(argc==1){
cout << "Usage: ./Diary add <date> <text>" << endl;
}
else{
Entry entry;
bool success = entry.write(argv[1], argv[2]);
}
return 0;
}
CSV.cpp
#include <iostream>
#include <fstream>
using namespace std;
class Entry {
private:
public:
bool write (char* date, char* text){
ofstream file;
file.open("../Diary.csv", ios_base::app);
file << date << "," << text << endl;
file.close();
return true;
}
};
CSV.hpp
#pragma once
class Entry{
private:
public:
bool write (char* date, char* text);
};
真的不确定问题出在哪里。有什么建议吗?
您 CSV.cpp 文件应该是这样的:
#include <iostream>
#include <fstream>
#include "CSV.hpp"
using namespace std;
bool Entry::write (char* date, char* text)
{
ofstream file;
file.open("../Diary.csv", ios_base::app);
file << date << "," << text << endl;
file.close();
return true;
}
并且您必须将 cpp
文件(Main.cpp
和 CSV.cpp
)和 link 编译为 target
(您的程序可执行文件。)