Linux C/C++编译和使用so共享库

本文给出一个Linux C 编译和使用共享库so的一个小例子。如下:
文件 my_math.c

// @file: my_math.c
#include "my_math.h"

int add(int a, int b)
{
    return a + b;
}
// @file: my_math.h
int add(int a, int b);

文件 test.c

// @file: test.c
#include <stdio.h>
#include "my_math.h"

int main()
{
    int a = 1, b = 1, re;
    re = add(a, b);
    printf("1 + 1 = %d\n", re);
    return 0;
}

编译的方法:
链接器参数说明:Options for Linking

.PHONY: all
all : libmymath.so test

libmymath.so : my_math.o
    $(CC) -shared -o $@ $^     # 库文件以lib开始; 共享库文件以.so为后缀; -shared生成共享库

my_math.o : my_math.c
    $(CC) -c -fPIC -o $@ $^     # -c只编译不链接; PIC: Position Independent Code

# -l<lib_name> 指定编译期需要链接的共享库名字
# -L<lib_dir>  指定编译期需要链接的共享库路径
# -Wl,rpath=<lib_dir> 指定运行期共享库的路径
# -Wl,option 传递参数给linker
test : test.c
    $(CC) -o $@ $^ -lmymath -L. -Wl,-rpath=.
    # export LD_LIBRARY_PATH=.  # 如果编译期不用rpath,也可以在运行期指定so路径给操作系统
    ./test
    ldd test  # 显示依赖库

.PHONY: clean
clean:
    rm -v *.so *.o test

运行结果,在当前的目录执行make即可:

root@ubuntu:/media/psf/Home/iLearn/learn_so# make
cc -c -fPIC -o my_math.o my_math.c     # -c只编译不链接; PIC: Position Independent Code
cc -shared -o libmymath.so my_math.o     # 库文件以lib开始; 共享库文件以.so为后缀; -shared表示生成一个共享库
cc -o test test.c -lmymath -L. -Wl,-rpath=.
# export LD_LIBRARY_PATH=.  # 如果编译期不用rpath,也可以在运行期指定so路径给操作系统
./test
1 + 1 = 2
ldd test  # 显示依赖库
    linux-vdso.so.1 =>  (0x00007fff9e377000)
    libmymath.so => ./libmymath.so (0x00002b061fbd0000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00002b061fdd2000)
    /lib64/ld-linux-x86-64.so.2 (0x00002b061f9ab000)

猜你喜欢

转载自blog.csdn.net/thisinnocence/article/details/79124306