PersianGulf
PersianGulf

Reputation: 2935

How can I share a struct in OOP program?

I'm writing a code that it's OOP and I need to share a struct between files. I put my struct at end of my .h file and include it. Such as:

struct icsData
{
    AudioBuilder *audioBPtr;
}icsDataPtr;

Then I got the following errors:

NetworkSocket.o:(.bss+0x0): multiple definition of `icsDataPtr'
main.o:(.bss+0x0): first defined here
AudioCore.o:(.bss+0x10): multiple definition of `icsDataPtr'
main.o:(.bss+0x0): first defined here
AudioBuilder.o:(.bss+0x0): multiple definition of `icsDataPtr'
main.o:(.bss+0x0): first defined here
AudioInterface.o:(.bss+0x0): multiple definition of `icsDataPtr'
main.o:(.bss+0x0): first defined here
ChannelEndpoint.o:(.bss+0x0): multiple definition of `icsDataPtr'
main.o:(.bss+0x0): first defined here
Device.o:(.bss+0x0): multiple definition of `icsDataPtr'
main.o:(.bss+0x0): first defined here
MainCore.o:(.bss+0x0): multiple definition of `icsDataPtr'
main.o:(.bss+0x0): first defined here
MicroHandShake.o:(.bss+0x0): multiple definition of `icsDataPtr'
main.o:(.bss+0x0): first defined here
FrameBuilder.o:(.bss+0x0): multiple definition of `icsDataPtr'
main.o:(.bss+0x0): first defined here
RealTimeStatus.o:(.bss+0x0): multiple definition of `icsDataPtr'
main.o:(.bss+0x0): first defined here
collect2: error: ld returned 1 exit status
make: *** [eCom] Error 1

Question: Can I share it?

Upvotes: 0

Views: 103

Answers (2)

Mario
Mario

Reputation: 36517

You have to use the extern keyword, then define it in one translation unit:

Header file:

struct icsData
{
    AudioBuilder *audioBPtr;
};

extern icsData icsDataPtr;

Some cpp file:

icsData icsDataPtr;

Just note that this isn't really object oriented. You might want to create a static class providing one instance of the pointer or simply make the class a singleton, depending on how many common objects you'd like to share. Global objects or variables should be avoided if possible.

Upvotes: 1

Kiril Kirov
Kiril Kirov

Reputation: 38173

You need to define it on one place. Defining it in a header file, you'll have as many multiple definitions, as source files include that header file.

Define it in one cpp file, and use extern for the others. For example

// cpp1
struct icsData
{
    AudioBuilder *audioBPtr;
}icsDataPtr;


// cpp2
struct icsData;
extern icsData icsDataPtr;

Upvotes: 3

Related Questions