gpt4 book ai didi

c++ - 链接文件出错,VS 2015 中的错误 LNK2005

转载 作者:搜寻专家 更新时间:2023-10-31 02:18:15 24 4
gpt4 key购买 nike

问题是我将主要代码保存在一个文件中,并从另一个文件中调用函数。但是每次我尝试编译它时它都会给我 LNK 2005 错误。谁能帮我我在这里做错了什么?我是 C++ 的新手,所以请帮助我。

主文件

#include "stdafx.h"
#include "forwards.cpp" // All the functions are forwarded in this file.

int main()
{
using namespace std;
cout << "Approximate Age Calculator till 31-12-2015" << endl;
cout << endl;
cout << "Type your birth year: ";
cin >> yy;
cout << "Type your birth month: ";
cin >> mm;
cout << "Type your day of birth: ";
cin >> dd;
cout << "Your approximate age is ";
cout << yearCalculator() << " years, ";
cout << monthCalculator() << " months and ";
cout << daysCalculator() << " days" << endl;
cout << endl;
}

转发.cpp

#include "stdafx.h"
int dd;
int mm;
int yy;
int a;

int daysCalculator()
{
int a = 31 - dd;
return a;
}
int monthCalculator()
{
int a = 12 - mm;
return a;
}
int yearCalculator()
{
int a = 2015 - yy;
return a;
}

最佳答案

问题是您有一个 cpp 文件包含在另一个 cpp 文件中。但是 visual studio 试图将项目中的每个源文件构建为一个单独的翻译单元,然后将它们链接在一起。因此它编译了 forwards.cpp 两次。一次作为 main 的一部分,一次单独使用。这就是错误消息中出现重复的原因。最简单的修复,可能是删除#include。

您真正应该做的是创建一个 forwards.h,其中至少包含 forwards.cpp 中函数的原型(prototype),可能还有变量的 extern 语句。

您可能还应该考虑的另一件事是使用一个类来封装您拥有的变量。从另一个文件中自行导出变量通常不是好的形式。我可以举个例子。

#include <iostream>

using std::cout;
using std::cin;

// The class could be in another file
class AgeCalculator
{
int year_;
int month_;
int day_;

public:
AgeCalculator(int year, int month, int day)
: year_(year), month_(month), day_(day)
{}

int GetYear() { return (2015 - year_); }
int GetMonth() { return (12 - month_); }
int GetDay() { return (31 - day_); }
};

int main()
{
int y, m, d;

cout << "enter year :";
cin >> y;
cout << "enter month :";
cin >> m;
cout << "enter day :";
cin >> d;

AgeCalculator ac(y, m, d);

cout << "Your approximate age is " <<
ac.GetYear() << " years " <<
ac.GetMonth() << " months and " <<
ac.GetDay() << " days.\n";
}

关于c++ - 链接文件出错,VS 2015 中的错误 LNK2005,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34719961/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com