Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use global userdefined class object

Tags:

c++

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.

like image 700
Viku Avatar asked Nov 17 '25 12:11

Viku


2 Answers

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:

  1. Change class Friend { ... } frnd1; to class Friend { ... }; in Friend.h.
  2. Add extern Friend frnd1; to Friend.h;
  3. Change extern Friend frnd1; to Friend frnd1; in Friend.cpp.

Friend.h:

class Friend
{
  ...
};

extern Friend frnd1;

Friend.cpp:

#include "Friend.h"

Friend frnd1;
like image 132
NPE Avatar answered Nov 20 '25 02:11

NPE


extern Friend frnd1; goes in the header; Friend frnd1; goes in (one) .cpp file.

like image 37
melpomene Avatar answered Nov 20 '25 00:11

melpomene



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!