shared libraries in C++

Hi,
I have a files A.h, A.cpp, B.h and B.cpp that has declarations and definitions for classes A and B respectively. Class B uses some interfaces of class A. Now i want to create all these as shared library in linux. for this i used following commands
g++ -fpic -g -c -Wall A.cpp //this creates A.o
g++ -fpic -g -c -Wall B.cpp //this creates B.o
g++ -shared -Wl,-soname,libmystuff.so.1 -o libmystuff.so.1.0.1 A.o B.o // this creates shared library libmystuff.so.1.0.1

now i have written a test program in which i'm using the functions of class B using class B interface. When i compile my test program using the command
g++ -I ./header -L . Test.cpp
i get the errors like
: undefined reference to `A::functionA()'
Last edited on
You need to link to your shared lib.
g++ -I ./header -L . Test.cpp -l mystuff
Building shared libraries on linux use the GNU free compiler
1: Build your object files
$>gcc -fPIC -c FileA.c
$>gcc -fpic -c FileB.c
and so on. This will create the object files for your library.
2: Create the shared library (called MyShared.so)
$>gcc -shared FileA.o FileB.o -o MyShared.so
3: If you have root privileges you can place your newly created library
in a common place.
4: $>su -
root passwd
Ensure that the directory /usr/local/lib exists as this is where the
new library will be placed.
#>cp MyShared.so /usr/local/lib
Also check that the file /etc/ld.so.conf contains the line /usr/local/lib.
If it does not then enter it on a seperate line in the file.
5: Let the GNU compiler know about our new shared library
#>/sbin/ldconfig -v /usr/local/lib
6: exit root
$>Build your test file using the new library
$>gcc Mytest.c -o MyTest -lMyShared -lc
7: Use the 'ldd' command to see if your program found the new shared library
$>ldd MyTest
libMyShared.so => /usr/local/lib/MyShared.so (0x42000000)
libc.so.6 => ....
8: If it finds your library then we are finished.
9: If you don't have root privilges skip steps 4 to 8
You will need to use and export the LD_LIBRARY_PATH
$>export LD_LIBRARY_PATH=./
Now build your test file and run the 'ldd' list-dynamic-directories
$>gcc Mytest.c -o MyTest -lMyShared -lc
$>ldd MyTest
ldd should now find your library
libMyShared.so => /usr/local/lib/MyShared.so (0x42000000)
libc.so.6 => ....
Your program now work.
10: Read the man pages on any command you didn't understand.
Cheers mikeofthenight
Two small additions:
Don't use gcc if you want to compile or link a c++ program it won't link the c++ runtime (->Lining errors if you use C++).

$>export LD_LIBRARY_PATH=./
$>gcc Mytest.c -o MyTest -lMyShared -lc
might lead to unexpected results, you can also use

$>LD_LIBRARY_PATH=./ gcc Mytest.c -o MyTest -lMyShared -lc
Just FYI, there are other (arguably better) alternatives to using LD_LIBRARY_PATH. In my opinion, LD_LIBRARY_PATH is the easiest. If you are interested in other methods try Google.
Topic archived. No new replies allowed.