0

在 linux 上使用 g++ 编译时会出现错误 In function main': main.cpp:(.text+0x42): undefined reference toGradeBook::GradeBook(std::string)' collect2: error: ld returned 1 exit status

我正在使用此命令进行编译:

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

// gradebook.cpp
#include <iostream>
using namespace std;
#include "gradebook.h"

GradeBook::GradeBook( string name )
{
 setCourseName( name );
 maximumGrade = 0;
}

void GradeBook::setCourseName( string name )
{
 if ( name.length() <= 25 )
  courseName = name;
 else 
  {
   courseName = name.substr( 0, 25 );
   cout << "Name \"" << name << "\" exceeds maximum length (25).\n"
    << "Limiting courseName to first 25 characters.\n" << endl;
  } 
}

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

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

int maximum( int, int, int );
int maximumGrade;` 

void GradeBook::inputGrades()
{
 int grade1;
 int grade2;
 int grade3;
 cout << "Enter three integer grades: ";
 cin >> grade1 >> grade2 >> grade3;
}

int GradeBook::maximum( int x, int y, int z )`
{
 int maximumValue = x;
 if ( y > maximumValue )
  maximumValue = y;
 if ( z > maximumValue )
  maximumValue = z;
 return maximumValue;
}

void GradeBook::displayGradeReport()
{
 cout << "Maximum of grades entered: " <<  endl;
}

//成绩簿.h

#include <string>

using namespace std;

class GradeBook
{
 public:
  GradeBook (string);
  void setCourseName (string);
  string getCourseName ();
  void displayMessage();
  void inputGrades ();
  void displayGradeReport (); 
  int maximum (int, int, int);
 private:
  string courseName;
  int maximumGrade;
};

// main.cpp

#include "gradebook.h"

int main (int argc, char*argv[])
{
 GradeBook  myGradeBook ("Introduction to C++");
 return 0;
}
4

1 回答 1

3

GCC 的 -o 选项允许您指定可执行文件/库的名称,如

g++ -o foo.exe foo.cpp

您忘记在标志后添加名称,所以我假设它以gradebook.cpp 作为输出名称。

在你的情况下,它应该是

g++ -o my_prog gradebook.cpp main.cpp
于 2013-11-07T20:54:18.487 回答