ld:找不到个符号

ld: symbol(s) not found

本文关键字:符号 找不到 ld      更新时间:2023-10-16

我现在正在学习Ellis Horowitz编写的C++数据结构基础,试图实现第77页上的示例。然而,在我构建项目之后,Eclipse控制台显示了一些警告。

这是我的头文件:

#ifndef RECTANGLE_H_
#define RECTANGLE_H_
class Rectangle{
public:
Rectangle();
~Rectangle();
int GetHeight();
int GetWidth();
private:
int xLow, yLow, height, width;
} ;
#endif

这是我的源文件:

#include <iostream>
#include "Rectangle.h"
using namespace std;
int main(){
    Rectangle r, s;
    Rectangle *t = &s;
    if(r.GetHeight()*r.GetWidth() > t->GetHeight()*t->GetWidth())
        cout << "r";
    else
        cout << "s";
    cout << "has the greater area" << endl;
    return 0;
}

CDT构建控制台显示:

Building target: rectangle
Invoking: MacOS X C++ Linker
g++  -o "rectangle"  ./main.o   
Undefined symbols:
  "Rectangle::Rectangle()", referenced from:
      _main in main.o
      _main in main.o
  "Rectangle::GetWidth()", referenced from:
      _main in main.o
      _main in main.o
  "Rectangle::GetHeight()", referenced from:
      _main in main.o
      _main in main.o
  "Rectangle::~Rectangle()", referenced from:
      _main in main.o
      _main in main.o
      _main in main.o
      _main in main.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
make: *** [rectangle] Error 1
**** Build Finished ****

此外,二进制文件会在构建项目后自动创建吗?

Rectangle方法的实现真的不见了。

这就是你在链接器错误消息中看到的方法:

Rectangle::Rectangle()
Rectangle::GetHeight()
Rectangle::GetWidth()    

如果您有一个Rectangle.cpp(或.cc,.cxx)文件,则还需要编译该文件并链接Rectangle.o文件。

既然你问了,这里有一个简化的概述,不同的文件名结尾是什么:

  • 矩形。h是包含类接口的头文件。通常,如果我阅读并理解了这个文件,就可以使用那里定义的类了
  • Rectangle.cpp是实现或源文件,包含实现。您也可以将它们放在头中,但对于较大的类,这会使头文件更加拥挤,并带来一些其他缺点(编译时速度、封装较少…)
  • 矩形。o是对象文件。这是编译器从头文件和源文件中生成的内容,并由链接器使用

您还没有在任何地方定义Rectangle类函数。矩形.c在哪里?

头文件只是简单地声明类存在,但您没有为该类提供任何定义。你需要一个矩形。此外,您还必须链接到Rectangle.o.