0

In date.h, I wrote:

#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

and in date.cpp, I wrote:

#include "date.h"
Date::Date()
{
    time_t ltime = time(NULL);
    tm *today = localtime(&ltime);
    year = today->tm_year + 1900;
    month = today->tm_mon + 1;
    day = today->tm_mday;
}

There are no compiling error with this code, but I got a link time error when I tried to run this code:

undefined reference to `WinMain'
collect2.exe: error: ld returned 1 exit status

What has caused the error and how can I fix it?

1 Answers1

1

As other commented the problem is that you created a class which is not executable by itself. You created a library that you can use in other C++ programs, so it compiles fine but it cannot run by itself, that's why you get the error while trying to run the compiled binary. In C++ you have to execute the code of the classes from a main function.

The simplest way to fix it would be to add main.cpp:

#include "date.h"
int main(void){
   Date d = Date(2023, 1, 23);
   d.print();
}