Saweenbarra
Saweenbarra

Reputation: 3

Undefined reference to Class::Function linker error

Trying to build an executable from two .cpp files and one .h file but appear to be getting a linker error. This is the error I'm getting...

/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

And here's my code...

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);
};

Really not sure what the problem could be. Any tips?

Upvotes: 0

Views: 382

Answers (1)

Manuel
Manuel

Reputation: 2554

You CSV.cpp file should be like:

#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;
}

And you have to compile both cpp files (Main.cpp and CSV.cpp) and link to the target (your program executable.)

Upvotes: 1

Related Questions