简体   繁体   中英

simple c++ code does not compile (linker command failed with exit code 1)

I'm new to C++ and studying the Dietel book. On the book, it has some example codes for classes and interfaces

Gradebook.h

#ifndef GradeBook_h
#define GradeBook_h


#endif /* GradeBook_h */


#include <string>

class GradeBook
{
    public:
    explicit GradeBook( std::string );
    void setCourseName( std::string );
    std::string getCourseName() const;
    void displayMessage() const;

private:
    std::string courseName;
};

Gradebook.cpp

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

using namespace std;


GradeBook::GradeBook( string name )
{
    courseName = name;
}

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

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

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

main.cpp

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

using namespace std;

int main()
{
    GradeBook gradeBook1("CS 101 Introduction to C++ Programming");
    GradeBook gradeBook2("CS 102 Data Structures in C++");

    cout << "gradeBook1 : " << gradeBook1.getCourseName() << endl;
    cout << "gradeBook2 : " << gradeBook2.getCourseName() << endl;

}

So, I am trying to compile this on my mac terminal using g++ main.cpp -o example.out . But it seems that this constantly gives me an error saying that

Undefined symbols for architecture x86_64: "GradeBook::GradeBook(std::__1::basic_string, std::__1::allocator >)", referenced from: _main in main-0602c7.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)

I have tried getting rid of most of the function declarations and function implementations except for the constructor and the member variable, but it seems to be giving me the same error still.

I think I copied the code exactly from the book, but I do not understand what I am doing wrong. Any help would be appreciated.

You'll have to compile all sources, so add your GradeBook class implementation too

g++ main.cpp GradeBook.cpp -o example.out
             ~~~~~~~~~~~~~

As already mentioned in above example, you have to mention both source files (main.cpp and GradeBook.cpp) while compiling the code.

This will work.

However, there is one more potential problem in your code.

#ifndef GradeBook_h
#define GradeBook_h


#endif /* GradeBook_h */

There is no code inside ifndef-endif guard. You need to put the complete code in .h file inside ifndef-endif. Otherwise when you work on a larger project and GradeBook.h is getting included from multiple places, you might get redeclaration error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM