We all use library functions in the programs we write. An example of library that is always used in Solaris and Unix like Operating systems is libc.so. But how to create a library? It is not hard. A dynamic library can be easily created as shown in the following example.
Let's say we want to create a library called libgeek.so. It will contain an example function called my_library_func() that we will use in our program. We will create a simple program called geek.c that has the function we wanted. We will compile this as a library and call it libgeek.so (library names begin with lib) :
$ cat geek.c
my_library_func()
{
printf("Inside my library function");
}
The above is a library function we wanted to create. We then compile it into a dynamic library by giving a -G option to compiler :
$ cc -o libgeek.so -G geek.c
Now, we can use the generated library libgeek.so in our programs like:
$ cat hellolibrary.c
int main()
{
my_library_func();
return 0;
}
Now, we can compile our program and tell the linker to link to the library we created for my_library_func() :
$ cc hellolibrary.c -L/home/osgeek -R/home/osgeek -lgeek
L and R tell linker the path to look up during link-time and run-time to find library libgeek.so. The library libgeek.so is used with "lib" part removed and "l" prefixed as "lgeek".
When we run this program, the output would look like:
$ a.out
Inside my library function
That's it. We created a library and used it in a program.
Let's say we want to create a library called libgeek.so. It will contain an example function called my_library_func() that we will use in our program. We will create a simple program called geek.c that has the function we wanted. We will compile this as a library and call it libgeek.so (library names begin with lib) :
$ cat geek.c
my_library_func()
{
printf("Inside my library function");
}
The above is a library function we wanted to create. We then compile it into a dynamic library by giving a -G option to compiler :
$ cc -o libgeek.so -G geek.c
Now, we can use the generated library libgeek.so in our programs like:
$ cat hellolibrary.c
int main()
{
my_library_func();
return 0;
}
Now, we can compile our program and tell the linker to link to the library we created for my_library_func() :
$ cc hellolibrary.c -L/home/osgeek -R/home/osgeek -lgeek
L and R tell linker the path to look up during link-time and run-time to find library libgeek.so. The library libgeek.so is used with "lib" part removed and "l" prefixed as "lgeek".
When we run this program, the output would look like:
$ a.out
Inside my library function
That's it. We created a library and used it in a program.
No comments:
Post a Comment