0
votes

I have to build a single shared library from multiple object files. Lets say object file Obj1.o and Obj2.o kept under obj_folder and both use a common function foo(). function foo() is defined in another cpp file lets call it foo.cpp. The ibject of foo.cpp is also present under obj_folder.

Scenario is as below:

In obj1.cpp
void func1()
{
int timestamp =foo();
}

in obj2.cpp
void func2()
{
int timestamp = foo();
}

Both files have their obj1.o and obj2.o build separately. What my thinking here is both obj1.o and obj2.o have statically build code for foo() and while in building linker just cant find from which object it should pick foo() location.

building shared object project.so i use following command -

gcc -shared -fPIC obj_folder/*.o -o project.so

building shared object i see error message -

Multiple definition of foo()

How i can resolve this symbol collision and build my shared librray?

1
Do Obj1 and Obj2 define their own copies of foo? If so you should only define one copy (in either obj1 or obj2 but NOT both), place a prototype for foo in a header using the extern keyword (and include it when needed). - Michael Petch
you simply can't define 2 times the same function in one prog or lib. Do you really have defined it 2 times? Why? - Klaus
I have edited my question a bit. I have given more light on my understanding of the situation. - user3401643
Your question has no information about where/how foo is defined. - R.. GitHub STOP HELPING ICE
How many .o files are present in obj_folder? Any old ones that also include foo()? How are your obj1 and obj2 modules made aware of the declaration of foo()? (You're not #include-ing .cpp files, are you?) - sjnarv

1 Answers

0
votes

Multiple definition of foo()
How i can resolve this symbol collision and build my shared librray?

Unfortunately you have not provided enough info to answer that question.

Your description appears to imply that foo is defined in foo.o, but if that was so, you wouldn't get the link error you are getting.

The first step is therefore to find out where foo is actually defined. Here is the recipe to do so:

nm -A obj_folder/*.o | grep ' foo$'

For the link error to make sense, there should be two separate .o files with foo defined in each one. When linking you library, you'll have to get rid of one of them.

P.S. Don't call directories a "folder".

P.P.S. Linking a library like so: gcc ... obj_folder/*.o -o project.so is a really bad idea(TM). Learn and use make.