linux 编译c程序与动态链接库

时间:2022-01-26 15:53:05

linux 下编译c程序与动态链接库

1 动态库h文件和c文件

1.1 h 文件: kaflog4c.h

/**
* kaflog4c.h
*/
#include <stdio.h>
#include <stdlib.h>

void hello(const char *msg);

1.2 c 文件: kaflog4c.c

/** * kaflog4c.c */#include "kaflog4c.h"void hello(const char *msg){    printf("Hello %s!\n", msg);}

2 编译要产生动态库和静态库

2.1 编译动态库:libkaflog4c.so

$ gcc -W -Wall -fPIC -ansi -pedantic -I. -c kaflog4c.c$ gcc -shared kaflog4c.o -o libkaflog4c.so

2.2 编译静态库:libkaflog4c.a

$ ar r libkaflog4c.a kaflog4c.o

3 程序文件

3.1 main.c

编译要产生链接到动态库(libkaflog4c.so)的程序和静态库(libkaflog4c.a)的程序

/** * main.c */#include "kaflog4c.h"int main (){    hello("cheungmine");    return 0;}

1) 编译链接到动态库libkaflog4c.so的测试程序main:

$ gcc -W -Wall -ansi -pedantic -I. -c main.c$ gcc main.o -o main ./libkaflog4c.so# 查看依赖$ ldd ./main# 运行$ ./main

2) 编译链接到静态库libkaflog4c.a的测试程序main:

$ gcc main.o -o main ./libkaflog4c.a$ ldd ./main# 此时删除libkaflog4c.a和libkaflog4c.so对下面的执行无影响$ ./main

3.2 main_dl.c

/** * main_dl.c */#include "kaflog4c.h"#include <dlfcn.h>void dl_hello(){    void *dp;    void (*fn_hello)(const char*);    dp = dlopen("libkaflog4c.so", RTLD_LAZY);    if (!dp) {        printf("%s\n", dlerror());        exit(1);    }    fn_hello = dlsym(dp, "hello");    if (!fn_hello) {        printf("%s\n", dlerror());        exit(1);    }    fn_hello("cheungmine: load library when running");    dlclose(dp);}int main(){    dl_hello();    return 0;}

编译运行时动态加载动态库libkaflog4c.so的程序

(libkaflog4c.so已经存在于当前目录下)

$ gcc -W -Wall -ansi -I. -c main_dl.c$ gcc main_dl.o -o main_dl -ldl$ ldd main_dl$ ./main_dl$ sudo mv ./libkaflog4c.so /usr/local/lib/$ ./main_dllibkaflog4c.so: cannot open shared object file: No such file or directory$ sudo ldconfig$ ./main_dl