 |
NickSoft Linux Cookbook Quick howto's, Real live examples.
|
|
View previous topic :: View next topic |
Author |
Message |
NickSoft Site Admin

Joined: 13 Nov 2006 Posts: 22
|
Posted: Mon Jul 16, 2007 1:44 pm Post subject: Creating a shared and static library with GCC |
|
|
The code for the library
helloworld.c:
Code: | #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");
} |
The header file
helloworld.h:
Create object file:
Code: | gcc -c helloworld.c -o helloworld.o |
Create static library
Code: | ar rcs libhello.a helloworld.o |
Create shared library
gcc -shared -o libhello.so helloworld.o
A program using the library
main.c:
Code: | #include <stdio.h>
#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:
Code: | 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
Code: | LD_RUN_PATH=`pwd`
gcc main.c -o dynamically_linked -L. -lhello |
or use -rpath linker option
Code: | gcc main.c -o dynamically_linked -Wl,-rpath,$PWD -L. -lhello |
You can check if linking is successful with ldd:
Code: | 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 |
|
Back to top |
|
 |
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
|