140 likes | 327 Views
Creating a Shared Library. How you can create and use your own object-code libraries within the Linux environment. Building an executable file. source text. linker. compiler. object code. executable file. Translates programming language statements into cpu’s machine-language
E N D
Creating a Shared Library How you can create and use your own object-code libraries within the Linux environment
Building an executable file source text linker compiler object code executable file Translates programming language statements into cpu’s machine-language instructions Adjusts any memory references to fit the Operating Sytem’s memory model
Example: source text in assembly .data msg: string “ Hello \n” .text main: movl $4, %eax movl $1, %ebx movl $msg, %ecx movl $8, %edx int $0x80 ret .globl main
Compiling the source text $ gcc –c hello.s ; compile $ ld hello.o –o hello ; link
Normally need a runtime library source text compiler object file linker executable file object code library A previously compiled collection of standard program functions
How to build/use an archive file • $ gcc –c func1.c • $ gcc –c func2.c • $ ar cr myarchive.a func1.o func.o • $ g++ myapp.cpp myarchive.a –o myapp
Static versus Dynamic Linking • $ gcc –c hello.s • $ ld –static hello.o –o hello or • $ ld –shared hello.o –o hello
Smaller is more efficient objject file object file static linking function library function library executable files object file object file dynamic linking pointer pointer shared function library
Building a ‘Shared Library’ • Functions must be ‘reentrant’ • This implies: No global variables • Code must be ‘position-independent’ • Can’t jump or call to fixed addresses • Can’t access data at fixed locations
Command-formats For building the shared library: $ gcc –c –fPIC func.c $ gcc –shared –fPIC func.o –o libfunc.so For linking application with shared library: $ g++ app.cpp -oapp –L. –lfunc –Wl,-rpath,.
Command-line options • You need the -L. option to tell the linker where to search the for your libxxx.so files • You need the -l option to tell the linker which shared object files to link with first • You need the -Wl option to tell gcc/g++ compilers to pass options on to the linker • See the man pages for additional details
Class Exercise • Compile the files ‘comb.c’ and ‘other.c’ • Build a shared library containing both • Compile the ‘uselib.cpp’ demo-program so it will be linked with your shared library • Run the ‘uselib’ demo-program and turn in a printout that shows its output