调用C++类对象与函数时出现Undefined Reference错误求助
C++链接器错误:未定义类成员函数引用
问题场景
使用Sublime Text编写《C++编程》示例7_15_17的代码,包含fig07_17.cpp、GradeBook.cpp与GradeBook.h三个文件,代码编写完成后编译出现链接错误。
代码文件
fig07_17.cpp
#include <array> #include "GradeBook.h" using namespace std; // function main begins program execution int main() { const array< int, GradeBook::students > grades = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 }; string courseName = "CS101 Introduction to C++ Programming"; GradeBook myGradeBook( courseName, grades ); myGradeBook.displayMessage(); myGradeBook.processGrades(); }
GradeBook.cpp
// Fig. 7.16: GradeBook.cpp #include <iostream> #include <iomanip> #include "GradeBook.h" using namespace std; GradeBook::GradeBook( const string &name, const array< int, students > &gradesArray ) : courseName( name ), grades( gradesArray ) { } void GradeBook::setCourseName( const string &name ) { courseName = name; } string GradeBook::getCourseName() const { return courseName; } void GradeBook::displayMessage() const { cout<< "Welcome to the grade book for\n" << getCourseName() << "!" << endl; } void GradeBook::processGrades() const { // output grades array outputGrades(); // call function getAverage to calculate the average grade cout << setprecision( 2 ) << fixed; cout << "\nClass average is " << getAverage() << endl; // call functions getMinimum and getMaximum cout << "Lowest grade is " << getMinimum() << "\nHighest grade is " << getMaximum() << endl; // call function outputBarChart to print grade distribution chart outputBarChart(); } // end function processGrades int GradeBook::getMinimum() const { int lowGrade = 100; // assume lowest grade is 100 // loop through grades array for ( int grade : grades ) { // if current grade lower than lowGrade, assign it to lowGrade if ( grade < lowGrade ) lowGrade = grade; // new lowest grade } // end for return lowGrade; // return lowest grade } // end function getMinimum int GradeBook::getMaximum() const { int highGrade = 0; // assume highest grade is 0 // loop through grades array for ( int grade : grades ) { // if current grade higher than highGrade, assign it to highGrade if ( grade > highGrade ) highGrade = grade; // new highest grade } // end for return highGrade; // return highest grade } // end function getMaximum // determine average grade for test double GradeBook::getAverage() const { int total = 0; // initialize total // sum grades in array for ( int grade : grades ) total += grade; // return average of grades return static_cast< double >( total ) / grades.size(); } // end function getAverage void GradeBook::outputBarChart() const { cout << "\nGrade distribution:" << endl; // stores frequency of grades in each range of 10 grades const size_t frequencySize = 11; array< unsigned int, frequencySize > frequency = {}; // init to 0s // for each grade, increment the appropriate frequency for ( int grade : grades ) ++frequency[ grade / 10 ]; for ( size_t count = 0; count < frequencySize; ++count ) { // output bar labels ("0-9:", ..., "90-99:", "100:" ) if ( 0 == count ) cout << " 0-9: "; else if ( 10 == count ) cout << " 100: "; else cout << count * 10 << "-" << ( count * 10 ) + 9 << ": "; // print bar of asterisks for ( unsigned int stars = 0; stars < frequency[ count ]; ++stars ) cout << '*'; cout << endl; // start a new line of output } } void GradeBook::outputGrades() const { cout << "\nThe grades are:\n\n"; // output each student's grade for ( size_t student = 0; student < grades.size(); ++student ) cout << "Student " << setw( 2 ) << student + 1 << ": " << setw( 3 ) << grades[ student ] << endl; }
GradeBook.h
#include <string> #include <array> class GradeBook { public: // constant -- number of students who took the test static const size_t students = 10; // note public data // constructor initializes course name and array of grades GradeBook( const std::string &, const std::array< int, students > & ); void setCourseName( const std::string & ); std::string getCourseName() const; void displayMessage() const; void processGrades() const; int getMinimum() const; int getMaximum() const; double getAverage() const; void outputBarChart() const; void outputGrades() const; private: std::string courseName; std::array< int, students > grades; };
错误信息
C:\Users\PC\AppData\Local\Temp\cciKxoUd.o:fig07_17.cpp:(.text+0xa5): undefined reference to `GradeBook::GradeBook(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::array<int, 10u> const&)' C:\Users\PC\AppData\Local\Temp\cciKxoUd.o:fig07_17.cpp:(.text+0xb5): undefined reference to `GradeBook::displayMessage() const' C:\Users\PC\AppData\Local\Temp\cciKxoUd.o:fig07_17.cpp:(.text+0xc2): undefined reference to `GradeBook::processGrades() const' collect2.exe: error: ld returned 1 exit status [Finished in 330ms]
解决方法
这个错误是链接器错误,核心原因是编译时仅处理了主文件fig07_17.cpp,没有将实现类成员函数的GradeBook.cpp一起编译链接,导致链接器找不到这些函数的具体定义。
方法1:命令行手动编译
打开命令提示符,进入代码所在目录,执行以下命令完成编译链接:
g++ fig07_17.cpp GradeBook.cpp -o GradeBook
编译完成后运行可执行文件:
# Windows系统 GradeBook.exe # Linux/MacOS系统 ./GradeBook
方法2:配置Sublime Text编译系统
- 点击Sublime Text菜单栏
Tools->Build System->New Build System... - 删除默认内容,粘贴以下配置:
{ "cmd": ["g++", "${file}", "GradeBook.cpp", "-o", "${file_base_name}"], "file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$", "working_dir": "${file_path}", "selector": "source.c++", "shell": true, "variants": [ { "name": "Run", "cmd": ["start", "${file_base_name}.exe"] } ] }
- 保存文件,命名为
C++ GradeBook.sublime-build - 点击菜单栏
Tools->Build System,选择刚刚创建的C++ GradeBook,按Ctrl+B编译,按Ctrl+Shift+B运行程序。
额外注意事项
检查GradeBook.cpp的文件名是否和代码引用一致,避免因大小写差异(如误写为Gradebook.cpp)导致编译器无法找到文件。
内容的提问来源于stack exchange,提问作者faik mermer
相关产品推荐
相关产品推荐

