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.


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

No comments:

Post a Comment