C Linux - Making Libraries - Static and Dynamic

We will be using two files namely main.c and hello.c as following:

//Filename : hello.c
#include <stdio.h>
void hello()
{
printf("\n in hello.c hello .... \n");
}

//Filename : main.c
#include <stdio.h>
int main()
{
printf("\n in main.c calling hello \n");
hello();
}

1) Static Library

#gcc -c -fPIC hello.c -o hello.o
#ar rcs libhello.a hello.o

#gcc -static main.c -L. -lhello -o static_link_exe
#export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`pwd`

Run the application to test
#./static_link_exe

To verify that statically linked executable files statically linked libraries, you can do
#strings static_link_exe | grep hello

2) Dynamic Library / Shared Library

#gcc -c -fPIC hello.c -o hello.o
#gcc -shared -o libhello.so hello.o
#gcc main.c -o dynamic_link_exe -L. -lhello
#export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`pwd`

Run the application to test
#./dynamic_link_exe

To verify that dynamically linked executable files share libraries, you can do
#strings dynamic_link_exe | grep hello

Also verify using ldd
#ldd dynamic_link_exe
libhello.so => ./libhello.so
libc.so.1 => /lib/libc.so.1
libgcc_s.so.1 => /usr/sfw/lib/libgcc_s.so.1
libm.so.2 => /lib/libm.so.2
/platform/SUNW,Ultra-80/lib/libc_psr.so.1

See the libhello.so file is linked here

No comments:

Books I like

  • Inside C++ Object Model
  • Unix Network Programming - Stevens
  • Professional-c++-programmer-to-programmer - wrox
  • Beautiful-code-leading-programmers-explain-how-they-think-theory-in-practice