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

标签 c++

问题是我将主要代码保存在一个文件中并从另一个文件调用函数。但每次我尝试编译它时都会出现 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/

相关文章:

c++ - 如何将变量(从类类型的对象)仅作为对象传递给函数(在 main.cpp 中)

c++ - 导致奇怪行为的共享指针

c++ - "stringstream"是否复制构造它的字符串?

c++ - 烟花opengl

c++ - const 的奇怪使用 - 为什么编译?

c++ - 仅 header 库 : use class defined later on in the header

c++ - cpp中字符串的动态内存分配

c++ - 列出 boost io_service 中的事件处理程序

C++,条件运算符结合性

c++ - 如何使用 bjam 在 cygwin windows7 i686-w64-mingw32-g++ 中编译 Boost(和链接?)库