Create static, dynamic libraries under Linux
Source
----------- A.CPP --------------- # include
----------- B.CPP ---------------- # include
Static library 1, compile generation A.O B.O file # g -c a.cpp b.cpp
2, generate Archive file libtest.a C- Create R- to add files to libtest.a # Ar RC Libtest.a A.O B.O
3, specify the static library libtest.a to compile # g -o main main.cpp libtest.a
Run the result #./a.outin a (int a) 5in int b (char * s): Okin Main
Copy the code directly in LibTest.a is equivalent to static compilation
Dynamic library 1, compile generation A.O B.O file-FPIC generation .o file-free time-independence # g -fpic a.cpp b.cpp
2, generate dynamic library libtest.so # g -shared -o libtest.so a.o B.O
3, specify dynamic library libtest.so to compile # g main.cpp ./libtest.so
View Dynamic Connection Library # ldd a.out ./libtest.so => ./libtest.so (0x40014000) libstdc - libc6.2-2.so.so.3 => /usr/lib/libstdc -libc6.2-2. SO.3 (0x4002e000) libm.so.6 => /Lib/i686/libm.so.6 (0x40071000) libc.so.6 => /Lib/i686/libc.so. 6 (0x42000000) / lib / ld -Linux.SO.2 => /Lib/ld-linux.so.2 (0x40000000) /LIB/ld-Linux.SO.2 => /Lib/ld-linux.so.2 (0x40000000)
Other 1. Dynamic connection library 3 If # g main.cpp libtest.so compiles can be used but run error not found under the default library path # ./a.out./a.out: error while loading Shared libraries: libtest.so: Cannot Open Shared Object File: No Suchfile or Directory View connection library # ldd a.out libtest.so => NOT FOUND libstdc - libc6.2-2.so.3 => / usr / lib / LibSTDC - LiBC6.2-2.SO.3 (0x4002C000) libm.so.400 => /Lib/i686/libm.so. 6 (0x4006f000) libc.so.6 => /lib/i686/libc.so. 6 (0x42000000) /LIB/ld-Linux.SO.2 => /Lib/ld-Linux.SO.2 (0x40000000) 2, easy to use can copy static library libtest.a or dynamic library libtest.so to the default library Find path / lib or / usr / lib, compile direct # g main.cpp -ltest -l automatic library name extension # ldd a.out libtest.so => /usr/lib/libtest.so (0x4002b000 ) Libstdc - libc6.2-2.so. 3 => /usr/lib/libstdc -libc6.2-2.so. 3 (0x4002e000) libm.so.6 => /lib/i686/libm.so.6 (0x40071000) libc.so.6 => /Lib/i686/libc.so.6 (0x42000000) /Lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000) Static # g main.cpp --ltest # ldd a.out libstdc - libc6.2-2.so.3 => / usr / lib / libstdc - libc 6.2-2.SO.3 (0x4002B000) libm.so.6 => /Lib/i686/libm.so.6 (0x4006f000) libc.so.6 => /Lib/i686/libc.so.6 (0x42000000) /LIB/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000)
3, 2 Generate Archive in Static Library May Need RanLib LibTest.a to write content to write content to LDEST.A for LD connection
4, the -l option is behind the compiled file, in the previous error # g -ltest main.cpp / tmp / ccbqk3ky.o: in function `main ': / tmp / ccbqk3ky.o (.text 0xc) : undefined Reference to `a (int) '/ tmp / ccbqk3ky.o (.text 0x1c): undefined reference to` b (char *)' Collect 2: ld Returned 1 Exit Status