Prz9 Prz9 - 1 year ago 117
C Question

Multiple definition error while linking two object files with same definition

Basically my prob is this :

I have a header file -

foo.h
with a structure pointer
human *person = NULL
in it. The definition for structure
human
is in another header included within foo.h . I am creating a shared object file
game.so
using
foo.h
and few other headers and cpps.

Now , I have two different cpp files -
a.cpp
and
b.cpp
which include the header foo.h.
I am creating an object file
a.o
separately and
b.o
separately.
I am linking both the object file and
game.so
for creating another shared object file
tennis.so
and while doing so , am getting multiple definition for the "person". I am aware that the multiple definition error is because
a.o
contains the structure definition for
person
, so does
b.o
.

I have used
#pragma once
in
foo.h
already.
a.o
is getting compiled separately and
b.o
is getting compiled separately. so i dont think #pragma once or ifdef will be useful here because both
a.cpp
and
b.cpp
includes
foo.h


I cant change the structure defintion in
foo.
h to any other cpp file due to some dependencies while creating
game.so


Is there any other way to resolve the multiple definition error I get while creating
tennis.so
?

Answer Source

You need to make sure the person variable is only defined once. To do that, you need to only declare that variable in foo.h:

extern human *person;

Then, in foo.cpp, you define it:

human *person = NULL;

You then include foo.o in the object files that make up game.so.

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