zoukankan      html  css  js  c++  java
  • 生成并调用so动态库

    本文更新于2019-01-03。

    生成库

    头文件fn.h如下:

    #ifndef __FN_H__
    #define __FN_H__
    
    #ifdef __cplusplus
    extern "C"
    {
    #endif
    
    typedef int (*FnAdd)(int a, int b);
    
    int add(int a, int b);
    
    #ifdef __cplusplus
    }
    #endif
    
    #endif // __FN_H__
    

    源文件fn.c如下:

    #include "fn.h"
    
    int add(int a, int b) {
    	return a+b;
    }
    

    编译生成libfn.so库:

    gcc -fPIC -shared fn.c -o libfn.so
    

    若不使用extern "C",且使用g++编译或使用gcc编译cpp文件,则生成C++形式的库。

    调用库

    源文件main.c如下:

    #include <stdio.h>
    #include <stdlib.h>
    #include <dlfcn.h>
    
    #include "fn.h"
    
    int main() {
    	void* handle = dlopen("./libfn.so", RTLD_LAZY);
    	if (handle == NULL) {
    		printf("dlopen: %s
    ", dlerror());
    		return -1;
    	}
    	
    	FnAdd add = (FnAdd)dlsym(handle, "add");
    	if (add == NULL) {
    		printf("dlsym: %s
    ", dlerror());
    		return -1;
    	}
    	
    	int a = 1;
    	int b = 2;
    	printf("add %d+%d=%d
    ", a, b, add(a, b));
    
    	dlclose(handle);
    	return 0;
    }
    

    编译生成可执行文件a.out:

    gcc -rdynamic -ldl main.c -o a.out
    

    如使用dlopen调用库时没指定库文件路径,只指定库文件名(如libfn.so),则执行程序前需导出环境变量LD_LIBRARY_PATH,将库文件所在目录加入其中。

    export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:dir
    
  • 相关阅读:
    HDU3371--Connect the Cities
    HDU1232--畅通工程
    HDU1102--Constructing Roads
    HDU1856--More is better
    HDU1325--Is It A Tree?
    HDU1272--小希的迷宫
    HDU1213--How Many Tables
    lnmp 实现owncloud
    lemp 编译安装 不完整版
    dns 视图
  • 原文地址:https://www.cnblogs.com/garvenc/p/build_and_call_so_library.html
Copyright © 2011-2022 走看看