Undefined reference when compiling multiple files

0

I'm learning C ++, and I have a question about creating classes in different files. I created the header with function prototypes, then as member functions in another cpp file.

When I test the files next to a main I get the following error:

undefined reference to GradeBook::GradeBook(std::string) linha 14
undefined reference to GradeBook::getNomeCurso() linha 16

This is the header with the gradebook class: gradebook.h

#include <iostream>
#include <string>

using namespace std;

class GradeBook
{
public:
    GradeBook( string );
    void setNomeCurso(string);
    string getNomeCurso();
    void mostrarMensagem();

private:
    string nome_curso;
};

This is the file called gradebook.cpp with member functions in it:

#include <iostream>
#include "gradebook.h"

using namespace std;

GradeBook::GradeBook( string z ){
   setNomeCurso(z);
}

void GradeBook::setNomeCurso( string nome ){
    nome_curso = nome;
}

string GradeBook::getNomeCurso(){
    return nome_curso;
}

void GradeBook::mostrarMensagem(){
    cout << "Bem vindo ao Livro de " << getNomeCurso() << "!" << endl;
}

And this is the test.cpp file with the Main function:

#include <iostream>
#include <string>
#include "gradebook.h"

using namespace std;

int main() {
    string curso;

    cout << "Entre com o nome do curso : ";
    getline(cin, curso);
    cout << endl;

    GradeBook Livro( curso );

    cout << "Bem vindo ao curso de " << Livro.getNomeCurso() << endl;

}
    
asked by anonymous 04.02.2014 / 19:44

3 answers

3

You should compile each .cpp file into an .o object. In sequence, link the objects to a final binary. Your problem occurs because you compiled only the main file and at the time of creating the executable some functions were missing (those of gradebook.cpp ). Assuming you are using GCC, do the following:

g++ -c main.cpp
g++ -c gradebook.cpp
g++ main.o gradebook.o -o programa

Or simply:

g++ main.cpp gradebook.cpp -o programa

Recommended reading: Creating your own header file (though this is about C, not C ++)

    
04.02.2014 / 20:05
2

Assuming you are using GCC or some compiler with similar interface, do, at the command line:

$ g++ -c gradebook.cpp -o gradebook.o
$ g++ Main.cpp gradebook.o -o <nome_do_programa>

You can make life easier by using GNU Make (for Linux) or tools like CMake that are compatible with Windows and do:

Makefile:

main: Main.cpp gradebook.o
    g++ $^ -o <nome_do_programa>

%.o: %.cpp
    g++ -c $^

At the command line:

$ make main
    
04.02.2014 / 20:05
0

Here it seems to be working.

g++ Main.cpp gradebook.cpp
    
04.02.2014 / 19:58