Datasheet
You can create and maintain your own static libraries very easily by using the ar (for archive) program
and compiling functions separately with
gcc -c. Try to keep functions in separate source files as much
as possible. If functions need access to common data, you can place them in the same source file and use
static variables declared in that file.
Try It Out Static Libraries
In this example, you create your own small library containing two functions and then use one of them in
an example program. The functions are called
fred and bill and just print greetings.
1. First, create separate source files (imaginatively called fred.c and bill.c) for each function.
Here’s the first:
#include <stdio.h>
void fred(int arg)
{
printf(“fred: we passed %d\n”, arg);
}
And here’s the second:
#include <stdio.h>
void bill(char *arg)
{
printf(“bill: we passed %s\n”, arg);
}
2. You can compile these functions individually to produce object files ready for inclusion into a
library. Do this by invoking the C compiler with the
-c option, which prevents the compiler
from trying to create a complete program. Trying to create a complete program would fail
because you haven’t defined a function called
main.
$ gcc -c bill.c fred.c
$ ls *.o
bill.o fred.o
3. Now write a program that calls the function bill. First, it’s a good idea to create a header file
for your library. This will declare the functions in your library and should be included by all
applications that want to use your library. It’s a good idea to include the header file in the files
fred.c and bill.c too. This will help the compiler pick up any errors.
/*
This is lib.h. It declares the functions fred and bill for users
11
Chapter 1: Getting Started
47627c01.qxd:WroxPro 9/28/07 8:56 PM Page 11