Translations of this page:

Creating a shared and static library with GCC

The code for the library


#include <stdio.h>
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");


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


#include <stdio.h>
#include "helloworld.h"
int main(int argc, char* argv[]) {
  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

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

lcb/programming/shared-static.txt · Last modified: 09.11.2008 02:03 by npelov
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki