This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ******************************************************************************** | |
// 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; | |
} |
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