zycoactivtheory zycoactivtheory -4 years ago 75
C++ Question

Program keeps on giving such LNK errors

header.h

#include <iostream>
#include <vector>
#include <ctime>
#include <string>

using namespace std;

//vector <Account> bankAccounts; this is taken out.

extern vector <Account> bankAccounts; //edited




struct Account {
int accountNumber;
string lastName;
string firstName;
double accountbalance;
};

void menu(int*);
void makeAccount(vector <Account>&);


cpp

#include "Header.h"

void menu(int*);
void makeAccount(vector <Account>&);
vector <Account> bankAccounts; //edited


int main() {



int input = 0;
int *inputPtr = &input;


menu(inputPtr);

switch (input) {
case 1:
makeAccount(bankAccounts);

}
}


another cpp

#include "Header.h"

vector <Account> bankAccounts; edited;

void menu(int *inputPtr) {

int select = 0;

cout << "Welcome to MadeUp Banking. Select options below: \n";
cout << "\t 1. Make new account. \n";
cout << "\t 2. Display to an account. \n";
cout << "\t 3. Deposit to an account. \n";
cout << "\t 4. Withdraw from an account. \n";
cout << "\t 5. Print account. \n";
cout << "\t 6. Delete an account. \n";
cout << "\t 7. Quit. \n";
cout << "Selection: ";
cin >> select;
*inputPtr = select;

}



void makeAccount(vector <Account> bankAccounts) {
//edited vector <Account> bankAccounts within makeAccount()

return;


}

When program is ran, the error gives:


main_file.obj : error LNK2005: "class std::vector > bankAccounts" (?bankAccounts@@3V?$vector@UAccount@@V?$allocator@UAccount@@@std@@@std@@A) already defined in function_file.obj
1>main_file.obj : error LNK2019: unresolved external symbol "void __cdecl makeAccount(class std::vector > &)" (?makeAccount@@YAXAAV?$vector@UAccount@@V?$allocator@UAccount@@@std@@@std@@@Z) referenced in function _main


How do I go about fixing this error?
Sorry I'm a rookie coder, if more details are needed, then please tell me and I will edit accordingly. Thank you for the help in advance.

Answer Source

1. bankAccounts already defined in function_file.obj.

You should define bankAccounts in your cpp file. Because if you define it in header file, when you include your header in multiple cpp files, there would be multiple definition of backAccounts.

If you needs it in multiple cpp files, use extern to declare(not define) it in your header file:

extern vector <Account> bankAccounts;

And in one of your cpp file, define it as:

vector <Account> bankAccounts;

2. unresolved external symbol void makeAccount()

Definition of makeAccount() should be like:

void makeAccount(vector <Account>&)
{
   // do something
}

While you are defining it as void makeAccount(vector<Account>). Please notice the difference. In your declaration, parameter is reference to a vector, while in your definition, parameter is vector object.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download