- Info
Multiple object modules can be packed together into a single file called static library. It can be then passed to the linker. The linker builds the executable and copies the object modules from the library that are referenced by the program.
The static library was developed to workaround the disadvantages of linking a whole dynamic library (a program would contain the code for the whole library (waste of space) and also when it's loaded into memory, the memory will contain code for all the function in the library(waste of memory)). With a static library, at link time the linker will copy only the object modules that are referenced by the application (This reduces the size of executable on disk and also on memory!)
- Creating the library
- Building the library from 2 initial source files:
mult.c
/* no bounds checking*/ int mult(int a, int b) { return a*b; }
add.c
/* no bounds checking*/ int add(int a, int b) { return a+b; }
The 2 files are compiled with gcc -Wall -c add.c mult.c
Library is created with ar rcs libmyfunctions.a add.o mult.o
More details on parameters for the ar utility with man ar. Also, to list the content of the archive the command ar -t libmyfunctions.a is useful.
- Building the library from 2 initial source files:
- Linking
- One way: gcc -o executable-name prog.c -L/path/to/library-directory -lmyfunctions
- Or: gcc -o executable-name foo.c libmyfunctions.a
- One way: gcc -o executable-name prog.c -L/path/to/library-directory -lmyfunctions
- Testing
foo.c
#include <stdio.h> #include "myfunctions.h" int main() { printf("%d", add(1,3)); return 0; }
myfunctions.h
#ifndef __MYFUNCTIONS_H__ #define __MYFUNCTIONS_H__ int add(int a, int b); int mult(int a, int b); #endif /* MYFUNCTIONS_H */
Compiling and running:
$ gcc -o foo foo.c -L. -lmyfunctions $ ./foo
Monday, January 31, 2011
Create static library with GCC
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment