user5773230
user5773230

Reputation:

Error with a linked file, Error LNK2005 in VS 2015

The thing is I am keeping the main code in one file and calling functions from the other file. But it gives me LNK 2005 error every time I try to compile it. Can anyone please help me what I am doing wrong here? I am a newbie in C++ so please help me.

main file

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

Upvotes: 2

Views: 170

Answers (1)

Paul Rooney
Paul Rooney

Reputation: 21609

The issue is that you have a cpp file included in another cpp file. But visual studio tries to build each source file in the project as a separate translation unit and then link it all together. So hence it compiles forwards.cpp twice. Once as part of main and once by itself. This is the reason for the duplications in the error messages. Simplest fix, is probably to remove the #include.

What you should really do is create a forwards.h that includes prototypes for the functions in forwards.cpp at least and probably extern statements for the variables.

Another thing you should maybe also consider is using a class to encapsulate the variables you have. It's not normally good form to export variables on their own from another file. I can give you an example of this.

#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";
}

Upvotes: 2

Related Questions