This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?

(34个答案)


5年前关闭。




这是g++的输入和产生的错误消息。
$ g++ main.cpp -o keyLogger
/tmp/ccvwRl3A.o:main.cpp:(.text+0x93): undefined reference to `SaveFeatures::SaveFeatures(std::string)'
/tmp/ccvwRl3A.o:main.cpp:(.text+0x93): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `SaveFeatures::SaveFeatures(std::string)'
/tmp/ccvwRl3A.o:main.cpp:(.text+0xbf): undefined reference to `SaveFeatures::save(std::string)'
/tmp/ccvwRl3A.o:main.cpp:(.text+0xbf): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `SaveFeatures::save(std::string)'
collect2: error: ld returned 1 exit status

我已经检查并重新检查了SaveFeatures类的.h和.cpp语法,但是还没有找到错误。任何帮助都将受到欢迎。

Main.cpp
#include <string>
#include "SaveFeatures.h"

using namespace std;

int main(){
    string fileName="saveTest.text";
    string saveContent="this is a test";
    SaveFeatures saveFeatures(fileName);
    saveFeatures.save(saveContent);
}

SaveFeature.cpp
#include "SaveFeatures.h"
#include <string>
using namespace std;

SaveFeatures::SaveFeatures(string fileName){
    setFileName(fileName);
}

void SaveFeatures::setFileName(string fileName){
    if(fileName!=NULL){
        this.fileName=fileName;
    }
}
bool SaveFeatures::save(string content){
    if(fileName==NULL)return false;
    if (content==NULL)return false;
    FILE *file;
    file=fopen(fileName,"a");
    if(file!=NULL){
        fputs(content,file);
    }
        return true;
}

string SaveFeatures::getFileName(){
    return fileName;
}

SaveFeatures.h
#ifndef SAVEFEATURES_H
#define SAVEFEATURES_H
#include <string>
using namespace std;

class SaveFeatures{
    public:
        SaveFeatures(string fileName);
        void setFileName(string fileName);
        string getFileName();
        bool save(string content);
    private:
        string fileName;
        //need to make a method to determine if the fileName has  file extension
};
#endif

谢谢各位女士的帮助

最佳答案

您将需要为可执行文件指定所有需要的源文件。

g++ main.cpp SaveFeature.cpp -o keyLogger

关于c++ - 未定义对[重复项]的引用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29338483/

10-11 16:50