Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function in one shared library calling a function in another shared library

I have a shared library say libfile2.so (which contains print2() function definition). Now I create a libfile1.so (which contains print1() function definition which in turn calls print2() function in libfile2.so). Now I create a main.c file which contains main() function which calls print1() by dynamically linking libfile1.so.

But I am getting the following error:

./libfile1.so: undefined reference to `print2'**

The following are the commands that I am using:

gcc -c -fpic file1.c
gcc -shared -o libfile1.so file1.o
gcc -c -fpic file2.c
gcc -shared -o libfile2.so file2.o
export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH
gcc -I. -L. -o main main.c -lfile1
like image 634
Sunil Avatar asked Dec 05 '25 14:12

Sunil


1 Answers

If you have called only print1 in your main.c. Then set the path of the libfile2.so in the LD_LIBRARY_PATH. Because it will try to find the dependencies of libfile1.so while linking with main.c.

gcc -o file1.o -c file.c
gcc -o file2.o -c file.c
gcc -o libfile2.so file2.o -shared
gcc -o libfile1.so file1.o -L. -lfile2 -shared
gcc -o main.o -c main.c
export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH
gcc -o main.exe main.o -L. -lfile1 

If you have called both print1 and print2 in main.c then link both libfile1.so and libfile2.so like below.

gcc -o main.o -c main.c
gcc -o main.exe main.o -L$YOUR_LIB_PATH -lfile1 -lfile2

Because all the symbol used in main.c needs to be resolved while generating executable.

like image 85
rashok Avatar answered Dec 07 '25 06:12

rashok



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!