use lib function on linux with C

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.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值