C++类代码编译正常却出现WinMain未定义链接错误,求原因及修复
链接错误:undefined reference to `WinMain' 的成因与修复
问题背景
编写了如下C++日期类代码:
date.h 代码
#ifndef DATE_H #define DATE_H #include <iostream> #include <ctime> class Date { int year,month,day; public: Date(); Date(int y, int m, int d) : year(y), month(m), day(d) {} ~Date() = default; int getYear() { return year; } int getMonth() { return month; } int getDay() { return day; } bool isLeapyear() { return (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0); } void print() { std::cout << year << "." << month << "." << day << std::endl; } }; #endif // DATE_H
date.cpp 代码
#include "date.h" Date::Date() { time_t ltime = time(NULL); tm *today = localtime(<ime); // 注意:原代码中的&ltime是HTML转义,实际需改为<ime year = today->tm_year + 1900; month = today->tm_mon + 1; day = today->tm_mday; }
编译无错误,但链接时出现以下错误:
undefined reference to `WinMain' collect2.exe: error: ld returned 1 exit status
错误成因
你当前的代码只实现了Date类的定义和构造函数,但缺少程序的入口函数。在Windows平台下(你使用的应该是MinGW编译器):
- 控制台程序的标准启动入口是
main()函数 - 如果编译器被配置为生成Windows GUI程序,会默认寻找
WinMain()作为入口
由于你的代码里既没有main()也没有WinMain(),链接器无法找到程序启动的入口点,因此抛出该链接错误。
另外注意date.cpp里有一处笔误:原代码中的&ltime是HTML转义字符,实际编写时需要改成<ime,否则会导致编译错误。
修复方案
方案1:添加控制台入口main()函数
新建main.cpp文件,写入测试代码来调用Date类:
#include "date.h" int main() { // 测试默认构造函数(获取当前系统日期) Date currentDate; std::cout << "当前日期:"; currentDate.print(); // 测试自定义日期构造 Date customDate(2023, 10, 1); std::cout << "自定义日期:"; customDate.print(); return 0; }
然后编译时将所有源文件一起编译,例如使用MinGW命令:
g++ date.cpp main.cpp -o date_program.exe
方案2:调整编译器编译目标(针对误配置GUI的情况)
如果你的编译器被错误设置为生成Windows GUI应用,可以在编译时添加-mconsole参数,强制编译器以控制台程序模式编译(寻找main()作为入口):
g++ date.cpp -mconsole -o date_program.exe
不过这种方法仅在你后续添加main()函数后才能让程序正常运行,否则程序仍无法执行逻辑。
内容的提问来源于stack exchange,提问作者Raine Huang
相关产品推荐
相关产品推荐

