Building C Library - Learning C by Example (2015)

Learning C by Example (2015)

7. Building C Library

This chapter explains how to build a library in C.

7.1 Getting Started

Sometimes we create some functions which are used for any application. We can create a library and use it in our C program. In this chapter, we try to build a library using C. There are two library type of library in C, static library and shared library.

7.2 Writing C Library

For illustration, we create a library by creating a file, called mysimplelib.c, and write this code.

#include <stdio.h>

int add(int a,int b){

return a+b;

}

int subtract(int a,int b){

return a-b;

}

int multiply(int a,int b){

return a*b;

}

Save this program.

After that, we create a header file for our library. Create a file, called mysimple.h, and write this code.

/*

header of libmysimple for static and shared libraries

*/

extern int add(int a,int b);

extern int subtract(int a,int b);

extern int multiply(int a,int b);

7.3 Compiling and Testing

In this section, we try to compile our library, mysimplelib.c, to be static library and shared library.

7.3.1 Static Library

Firstly, we compile our library, mysimplelib.c, to be a static library, called libmysimple.a .

$ gcc -c mysimplelib.c

$ ar rs libmysimple.a mysimplelib.o

ch7-1

To access our static library, we create a simple app. Create a file, called mysimpletest.c, and write this code.

#include <stdio.h>

#include "mysimple.h"

int main(int argc, const char* argv[]) {

int a,b,c;

a = 5;

b = 3;

c = add(a,b);

printf("%d + %d = %d\n",a,b,c);

c = subtract(a,b);

printf("%d - %d = %d\n",a,b,c);

c = multiply(a,b);

printf("%d * %d = %d\n",a,b,c);

return 0;

}

Consider our static library, libmysimple.a , and header file for library, mysimple.h are located into the same folder. Now you can compile and run this program.

$ gcc -I./ -L./ -o mysimpletest mysimpletest.c ./libmysimple.a

$ ./mysimpletest

A program output can be seen in Figure below.

ch7-2

7.3.2 Shared Library

We compile our library, mysimplelib.c, to be a shared library, called libmysimple.so . You can type the following commands.

$ gcc -c -fpic mysimplelib.c

$ gcc -shared -o libmysimple.so mysimplelib.o

ch7-3

To test our shared library, we can use the same program from mysimpletest.c .

Consider share library, libmysimple.so, and header file for shared library, mysimple.h, are located on the same folder.

You can compile and run our program.

$ gcc -I./ -L./ -o mysimpletest mysimpletest.c -lmysimple

$ ./mysimpletest

Program output:

ch7-4

You can modify shared library file location. For instance, we put our shared library file into /home/agusk/lib. We must add our library folder into LD_LIBRARY_PATH. Type this command.

export LD_LIBRARY_PATH=/home/agusk/lib:$LD_LIBRARY_PATH

Then, you can compile and run our program, mysimpletest .