简体   繁体   中英

C++ program in VCExpress has fatal error LNK1120

I have the declaration of a Date class in date.h, the definitions of the functions of the Date class in date.cpp, and the main program in test.cpp. I include the date.h header file on both cpp files and i have no idea why i get the following error:

1>------ Build started: Project: assignment1, Configuration: Debug Win32 ------
1>test.obj : error LNK2019: unresolved external symbol "public: void __thiscall   
Date::printDate(void)" (?printDate@Date@@QAEXXZ) referenced in function _main
1>test.obj : error LNK2019: unresolved external symbol "public: void __thiscall 
Date::setDate(int,int,int)" (?setDate@Date@@QAEXHHH@Z) referenced in function _main
1>C:\Users\chris\Desktop\c++\assignment1\Debug\assignment1.exe : fatal error LNK1120: 2 
unresolved externals

Here are my files:

//date.h
#include <iostream>

class Date {
public:
  void setDate(int a, int b, int c);
  void printDate();
private:
  int month;  //Number corresponding to month of year(e.g., 1-12)
  int day;    //Number corresponding to day of month(e.g., 1 to 28-31
  int year;   //Number corresponding to year
};


//date.cpp

#include "date.h"

/* a is month
   b is day
   c is year
*/

void Date::setDate(int a, int b, int c)
{
    bool incorrect = false;

    if ( a >= 1 && a <= 12)
        month = a;
    else
        incorrect = true;

    if ( b >= 1 && b <= 31)
        day = b;
    else
        incorrect = true;

    if ( c >= 1900 && c <= 2008)
        year = c;
    else
        incorrect = true;

    if (incorrect)
    {
        month = 9;
        day = 2;
        year = 2008;
    }
}

void Date::printDate()
{
    cout << month << "/" << day << "/" << year;
}


//test.cpp

#include <iostream>
using namespace std;
#include "date.h"
int main()
{
    Date d1;
    int m, d, y;
    cout << "Enter month, day and year separated by spaces: ";
    cin >> m >> d >> y;
    // call setDate
    d1.setDate(m,d,y);
    // call printDate
    d1.printDate();
    return 0;
}    

I believe that you have created a date.cpp file but it may not be part of the actual project. If it isn't added to the project the compiler and linker will not build/link it and this would cause the build failure you see above.

In Visual Studio Express open your project. Once your project is loaded, In the solutions explorer (pane) window you will see your application and items under it like "External Dependencies/Source Files/Header Files" etc. Right mouse click "Source files" then select "Add..". Then click on "Existing Item". Find date.cpp click it and click "Add" button. This will make sure date.cpp is part of the project and will be linked in.

Try to rebuild your application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM