VCExpress中的C++程序存在致命错误LNK1120

C++ program in VCExpress has fatal error LNK1120

本文关键字:致命错误 LNK1120 存在 程序 中的 C++ VCExpress      更新时间:2023-10-16

我有Date.h中Date类的声明,Date.cpp中Date类函数的定义,以及test.cpp中的主程序。我在两个cpp文件中都包含Date.h头文件,我不知道为什么会出现以下错误:

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:UserschrisDesktopc++assignment1Debugassignment1.exe : fatal error LNK1120: 2 
unresolved externals

这是我的文件:

//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;
}    

我相信您已经创建了一个date.cpp文件,但它可能不是实际项目的一部分。如果它没有添加到项目中,编译器和链接器将不会构建/链接它,这将导致您在上面看到的构建失败。

在Visual Studio学习版中打开您的项目。加载项目后,在解决方案资源管理器(窗格)窗口中,您将看到您的应用程序及其下的项目,如"外部依赖项/源文件/头文件"等。右键单击"源文件",然后选择"添加.."。然后单击"现有项目"。查找date.cpp点击它,然后点击"添加"按钮。这将确保date.cpp是项目的一部分,并将在.中链接

尝试重新生成应用程序。