Tuesday, February 7, 2012

_init and _fini (obsolete functions)

There are two special functions for library construction and destruction. Despite they are obsolete and replaced by generic constructor/destructor functions, they are used in a lot of libraries. Lets write a simple library with one some_func() function and with _init(), _fini() special functions.


// ********************************************************************************
// samplelib.h
#ifndef INCLUDED_SAMPLELIB_H
#define INCLUDED_SAMPLELIB_H
void some_func(void);
#endif//INCLUDED_SAMPLELIB_H
// ********************************************************************************
// samplelib.c
// system
#include <stdio.h>
// local
#include "samplelib.h"
//
void some_func(void)
{
printf("samplelib: some_func is called\n");
}
void _init(void)
{
printf("samplelib: _init is called\n");
}
void _fini(void)
{
printf("samplelib: _fini is called\n");
}
// ********************************************************************************
// main.c
// system
#include <stdio.h>
//
#include "samplelib.h"
//
int main(void)
{
//
printf("main: main is called\n");
//
some_func();
//
return 0;
}
view raw 3file.c hosted with ❤ by GitHub
In the above code there are 3 files: the library itself - samplelib.h, samplelib.c  and the application - main.c.

for compiling the library:
    $ gcc -fPIC -c samplelib.c
    $ gcc -nostartfiles -shared -o libsamplelib.so samplelib.o

Here -fPIC option is standing for position independent code. The -shared option is for shared library creation. By default gcc uses _fini () and _init() defined in crti.o, so -nostartfiles signals to gcc to not do that.
 And to compile the application we run the following.
    $ gcc -o main main.c -L. -lsamplelib
Here -L. option informs to gcc to search libraries in current directory, and -lsamplelib - to use libsamplelib.so shared library.

Finally by running the program the following will be outputted:
    samplelib: _init is called
    main: main is called
    samplelib: some_func is called
    samplelib: _fini is called