In Friend.h
#ifndef FRIEND
#define FRIEND
class Friend
{
public:
static int i ;
int j;
Friend(void);
~Friend(void);
}frnd1;
#endif
In Friend.cpp
#include "Friend.h"
int Friend::i = 9;
extern Friend frnd1;
Friend::Friend(void)
{
}
Friend::~Friend(void)
{
}
In main.cpp
#include <iostream>
using namespace std;
#include"Friend.h"
int main()
{
frnd1.j = 9;
cout<<"hello";
getchar();
return 0;
}
When I run the above code, its gives the following linker error:
error LNK2005: "class Friend frnd1" (?frnd1@@3VFriend@@A) already defined in main.obj
I am unable to understand how to use the global object in main function.
The problem is that frnd1 is defined in a header file, and thus ends up being instantiated in every translation unit.
What you want to do is declare it in the header file, and define it in the corresponding .cpp file:
class Friend { ... } frnd1; to class Friend { ... }; in Friend.h.extern Friend frnd1; to Friend.h;extern Friend frnd1; to Friend frnd1; in Friend.cpp.Friend.h:
class Friend
{
...
};
extern Friend frnd1;
Friend.cpp:
#include "Friend.h"
Friend frnd1;
extern Friend frnd1; goes in the header; Friend frnd1; goes in (one) .cpp file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With