There are two way of using lib function.
one is implicit call, by which the .so file is compiled together with the client code, and we just call the function in the lib file as a local function;
the other is the explicit call, by which we needn't compile the .so file, but we should explictly load the lib file and find the function inside the .so file.
I will introduce both method one by one.
Of cource, at first we should write the lib source file and compile it.
Here is the example code, myso.c
#include "stdio.h"
void show()
{
printf("Lib function called\n");
}
Compile it
gcc -fPIC -shared -o libmyso.so myso.c
-fPIC, means the the function name could be redirected.
-shared, means the output file will be a standard so file.
libmyso, comply the standard function naming , lib+name+.so
One, implictly lib function using
a. write the source code, just call the function "show" as a local function
such as : client.c
#include <stdio.h>
int main()
{
printf("Invoke my so\n");
show();
return 0;
}
b.compile it
gcc -o client client.c ./libmyso.so
./libmyso.so means the full path of the lib file.(in this example, the lib file and the source file are under the same direction)
c.OK
run it , and you'v done it.
Two, explictly lib function using.
a. write the source code. You need to load the lib by name explictly and find the function name explicitly.
the example code newcliet.c as belows
#include <stdio.h>
#include <dlfcn.h>
int main(int argc, char** argv)
{
void * pHandle;
void (*pFunc)();
pHandle = dlopen("libmyso.so",RTLD_NOW);
pFunc = (int(*)()) dlsym(pHandle, "show");
pFunc();
}
Of cource, you should check the result after you finish a function call.
b. compile it
gcc -o clientnew clientnew.c
c. run it
But make sure the path of the libfile is exactly the one you use in the source code.
Ok, finished.
I'll talk something about the libfile path in the next article.