In the C++ textbook I'm working through at the moment I'm up to an example where a class is being split into two files. One file, the classes "interface" (member function prototypes and data members) and the other is the implementation of these member functions. The third file in this program is the main function that uses objects of this class.
I'm using Visual studio 2010 to compile my programs, and instead of creating whole new projects for these programs, I am creating the source-code and header files and compiling them using Visual Studios command prompt using the "cl" command.
In this particular example, the class being split into two files is called "GradeBook", and as the name suggest, objects of this class represent a grade book.
Here's the header file for class GradeBook, containing member function prototypes and its data member.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
#include <string>
using namespace std;
class GradeBook
{
public:
GradeBook( string );
void setCourseName( string );
string getCourseName();
void displayMessage();
private:
string courseName;
};
|
This next files is the source-code file containing the implementation of GradeBooks member functions
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
#include <iostream>
#include "GradeBook.h"
using namespace std;
GradeBook::GradeBook( string name )
{
setCourseName( name );
}
void GradeBook::setCourseName( string name )
{
courseName = name;
}
string GradeBook::getCourseName()
{
return courseName;
}
void GradeBook::displayMessage()
{
cout << "Welcome to the Grade Book for\n"
<< getCourseName() << endl;
}
|
And finally, the file that contains the main function that creates GradeBook objects
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
#include <iostream>
#include <conio.h>
#include "GradeBook.h"
using namespace std;
int main()
{
GradeBook myGradeBook1( "CS101 Introduction to C++ programming" );
GradeBook myGradeBook2( "CS102 Data structures in C++" );
cout << "The first grade book is for " << myGradeBook1.getCourseName() << endl
<< "The second grade book is for " << myGradeBook2.getCourseName() << endl;
getch();
}
|
All these files are in the same directory, and when I go to compile the Main.cpp file (the one contain main) I get a linker error. I've also tried downloading this source code from the books website to see if that compiled and I got the exact same error, so I know there's nothing wrong with the code, so there must be something wrong with the way I'm compiling it.