====== Creating a shared and static library with GCC ======
===== The code for the library =====
helloworld.c:
#include
void hello() {
printf("Hello world!\n");
printf("Creating a shared and static library with GCC howto by NickSoft Linux Cookbook (http://lcb.croler.net/)\n");
}
helloworld.h:
#ifndef _HELLOWORLD_H
#define _HELLOWORLD_H
void hello();
#endif //_HELLOWORLD_H
Create object file:
gcc -c helloworld.c -o helloworld.o
===== Create static library =====
ar rcs libhello.a helloworld.o
===== Create shared library =====
gcc -shared -o libhello.so helloworld.o
===== A program using the library =====
main.c:
#include
#include "helloworld.h"
int main(int argc, char* argv[]) {
hello();
return 0;
}
===== Linking against static library =====
Static library is archive of .o files, so we add them to gcc command line as we would add object files:
gcc -c main.c
gcc main.o libhello.a -o statically_linked
**Note that** all *.o files must be listed before static library (libhello.a)
Don't get confused by **-static** gcc option - it tells gcc to link statically against all libraries - that include libc.a and other system libraries. Linking all libraries statically will increase size of your executable with about 400kb (this may vary for different versions of gcc/linux distributions). The "-static" linking is used when you need to run the executable in different linux distributions without recompiling it.
===== Linking against shared library =====
LD_RUN_PATH=`pwd`
gcc main.c -o dynamically_linked -L. -lhello
or use -rpath linker option
gcc main.c -o dynamically_linked -Wl,-rpath,$PWD -L. -lhello
You can check if linking is successful with ldd:
ldd dynamically_linked
ldd statically_linked
You can see that statically linked executable is linked to other shared libraries, but it is statically linked to libhello.a