动态加载共享库,这个知识点书上简单提了下,我做了个简单例子加深印象

main.c

#include  <stdio.h>
#include  
<dlfcn.h>

int main(int argc, char** argv)
{
void* handle = dlopen ("libreciprocal .so", RTLD_LAZY); 
double  (*reciprocal)(int= dlsym (handle, "reciprocal"); 
int  num;
num 
= atoi(argv[1]);
printf(“
%d 的倒数是%g\n”,num, reciprocal(num)); 
dlclose (handle); 
return 0;
}

reciprocal.hpp

#ifdef __cplusplus 
extern "C" {
#endif 
 
extern double reciprocal (int i); 
 
#ifdef __cplusplus 

#endif     

reciprocal.cpp

#include <cassert> 
#include 
"reciprocal.hpp" 
 
double reciprocal (int i) {
  
// I should be non-zero. 
  assert (i != 0); 
  
return 1.0/i; 

具体编译过程:

《Advanced Linux Programming》读书笔记(1)

注:这里我将共享库放置在/home/phinecos/lib下,

相关文章:

  • 2021-12-24
  • 2022-12-23
  • 2021-11-16
  • 2021-10-24
  • 2021-10-08
  • 2021-04-19
  • 2021-08-02
  • 2021-06-28
猜你喜欢
  • 2021-11-29
  • 2021-05-18
  • 2021-06-14
  • 2021-06-26
  • 2021-12-05
  • 2021-07-31
  • 2021-09-27
相关资源
相似解决方案