How to compile . cpp codes that have separate interfaces and implementations in g++?

Asked

Viewed 937 times

2

I’m studying C++ for the book Deitel, and I’m trying to compile a program where we have a file gradebook.h which is the interface, gradebook.cpp which is the implementation and test_gradebook_header_file.cpp which is the code containing the function main and the class instance GradeBook.

You’re making a mistake:

Undefined Reference to Gradebook::Gradebook

And that’s the same for the rest of the member functions, I’ve done everything as you teach, I’ve checked for any typos, but it’s all right. I suppose the problem is related to linkage. I want to use the g++ to do this but do not know the correct steps to follow.

Here is the interface:

#include <string>

using namespace std;

// interface da classe GradeBook
class GradeBook
{
public:
    GradeBook(string name_course_param);
    void setCourseName(string name_course_param);
    string getCourseName();
    void displayMessage();
private:
    string courseName;
}; 

Here is the implementation:

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

using namespace std;

GradeBook::GradeBook(string name_course_param)
{
    setCourseName(name_course_param);
}

void GradeBook::setCourseName(string name_course_param)
{
    courseName = name_course_param;
}

string GradeBook::getCourseName()
{
    return courseName;
}

void GradeBook::displayMessage()
{
    cout << "Welcome to the grade book for\n" << getCourseName()
      << "!" << endl;
}

Here is the program for testing:

// Utilizando a classe GradeBook incluindo o header file gradebook.h
#include <iostream>
#include "gradebook.h" // incluindo interface da classe

using namespace std;

int main(void)
{
    // criando duas instâncias da classe GradeBook
    GradeBook gradebook1("CS101 Introduction to C++ Programming");
    GradeBook gradebook2("CS102 Data Structures in C++");

    cout << "gradebook1 created for course: " << gradebook1.getCourseName()
      << "\ngradebook2 created for course: " << gradebook2.getCourseName()
      << endl;
}
  • 1

    Please include the source code of the files. The error says that you are not finding the Gradebook class. Beware of C/C case-sensitive++!

  • 1

    Also put the command line you are using to compile and connect.

1 answer

2


You are not compiling the class implementation...

g++ -o gradebook gradebook.cpp main.cpp
  • Thank you very much @José X., it helped me a lot. Now I will continue learning more. I thought I would have to resort to Ides to do this job. Thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.