C++错误 - 体系结构的未定义符号 x86_64:

C++ error - Undefined symbols for architecture x86_64:

本文关键字:x86 符号 未定义 错误 体系结构 C++      更新时间:2023-10-16

我正在学习C++,并且有一个简单的Date类,我正在尝试为Date设置一个值。

以下是源代码文件 -

日期.h

class Date{ 
private:
    int month;
    int day;
    int year;
public:
    Date();
    void setDate(int m, int d, int y);
};

和日期.cpp

#include "Date.h"
Date::Date()
{
    month = 1;
    day = 1;
    year = 80;
};
void Date :: setDate(int m1, int d1, int y1){
    month = m1;
    day = d1;
    year = y1;
};

但是,当我编译代码时,我收到错误消息 -

    Undefined symbols for architecture x86_64:
  "_main", referenced from:
      start in crt1.10.6.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status

有人可以帮忙吗?

谢谢

你缺少一个主函数。 将其添加到新文件(如 main.cpp,并在编译和链接时将其包含在)或其他 .cpp 文件中。

int main(int argc, char *argv[]) {  }

并将您的代码放在大括号中以运行程序。

每个 C/C++ 程序都必须有一个 main 函数,该函数无条件地用作程序执行的入口点。

int main(int argc, char** argv) {
  Date d;
  d.setDate(11, 19, 1984);
  /* do something with this date... */
  return 0;
}

一个常见的约定是将其放在 main.cc/main.cpp 中,并确保在这种情况下,main.cppDate.cpp 都被编译并链接到同一个目标二进制文件中。 如果无法解析main(int, char**),链接器将无法继续。 如果这对您来说很明显,那么我只需要求您检查链接器命令行以确保包含包含main的源/对象文件。

此外,随机C++最佳实践准则:您应该有一个非默认构造函数,该构造函数采用setDate执行的参数,并通过初始值设定项列表将它们分配给成员变量。在这种情况下,默认构造函数(无参数)对于具体日期类没有意义。