问题是我将主代码保存在一个文件中并从另一个文件调用函数。但是每次我尝试编译时它都会给我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;
}
forwards.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;
}
答案 0 :(得分:2)
问题是你有一个cpp文件包含在另一个cpp文件中。但是visual studio尝试将项目中的每个源文件构建为一个单独的翻译单元,然后将它们全部链接在一起。因此它编译forwards.cpp
两次。曾经作为主要的一部分和一次本身。这是错误消息中重复的原因。最简单的修复,可能是删除#include。
你应该做的是创建一个forwards.h
,其中包含forwards.cpp
中函数的原型,至少可能是变量的外部语句。
您应该考虑的另一件事是使用类来封装您拥有的变量。从另一个文件中自行导出变量通常不是好形式。我可以举个例子。
#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";
}