我有3個文件; main.cpp(包含main()),FileWriter.h和FileWriter.cpp。我在Debian Jessie上使用g ++(版本Debian 4.9.2-10)。我的項目包含'/ root/dev/Practice/src /'中的.cpp文件和'/ root/dev/Practice/include /'中的單個頭文件(FileWriter.h)。兩個目標文件的編譯工作,但鏈接到一個可執行文件抱怨未定義的引用main(),雖然我確實有一個看起來有效的'main.cpp'定義。g ++鏈接錯誤:未定義的引用'主'
這是我的make文件的輸出(這是在根目錄 '/根的/ dev /業務/' 目錄):
g++ -c -g -Wall -o src/FileWriter.o src/FileWriter.cpp g++ -c -g -Wall -o src/main.o src/FileWriter.cpp g++ src/FileWriter.o src/main.o -o bin/Practice /usr/lib/gcc/i586-linux-gnu/4.9/../../../i386-linux-gnu/crt1.o: In function '_start'" /build/glibc-J1NNmk/glibc-2.19/csu/../sysdeps/i386/start.S:111: undefined reference to 'main' collect2: error: ls returned 1 exit status Makefile:10: recipe for target 'bin/Practice' failed
這是我的main.cpp文件的內容:
#include <string>
#include <iostream>
#include "/root/dev/Practice/include/FileWriter.h"
int main() {
std::cout << "Hello!" << std::endl;
FileWriter * fw = new FileWriter("foofile");
fw->AddLine("CRAP!");
fw->AddLine("NO!");
return 0;
}
我FileWriter.h:
#ifndef FILEWRITER_H_
#define FILEWRITER_H_
#include <string>
#include <iostream>
class FileWriter{
public:
FileWriter(std::string);
~FileWriter();
void AddLine(std::string);
private:
std::string fileLocation;
std::ofstream *filestream;
};
#endif /* FILEWRITER_H_ */
...和我FileWriter.cpp:
#include "/root/dev/Practice/include/FileWriter.h"
#include <fstream>
// g++ linker error if 'inline' not included - why?
inline FileWriter::FileWriter(std::string fileName)
{
this->fileLocation = fileName;
const char * x = this->fileLocation.c_str();
this->filestream = new std::ofstream();
this->filestream->open(x, std::ios::out | std::ios::app);
}
inline FileWriter::~FileWriter()
{
this->filestream->close();
}
inline void FileWriter::AddLine(std::string line)
{
*this->filestream << line << std::endl;
}
爲什麼罵?這可能令人沮喪,但請不要在公開帖子中這樣做。 – Li357
@AndrewL他準備說這些話的時候,他意識到什麼時候他意識到問題所在...... –
這樣比較好:^) – Li357