动态库的引入及减少了主代码文件的大小,同时生成的动态库又是动态加载的,只有运行的时候才去加载,linux 下的 动态库 .so 就像windows下的 DLL一样。有关动态库的概念自行上网搜。一下是创建及引用动态库
test_so.h
#ifndef TEST_SO_H
#define TEST_SO_H
void test_A();
void test_B();
#endif
test_a.c
#include <stdio.h>
#include "test_so.h"
void test_a()
{
printf("%s, %d\n", __func__, __LINE__);
}
test_b.c
#include <stdio.h>
#include "test_so.h"
void test_b()
{
printf("%s(), %d\n",__func__, __LINE__);
}
test.c
#include <stdio.h>
#include "test_so.h"
void main()
{
printf("%s():%d\n",__func__, __LINE__);
test_a();
test_b();
}
Makefile
#!/bin/sh
file_1 := test_a.c
file_2 := test_b.c
main_file := test.c
out_file := test
daymic_lib := .so
out_so_name := lib$(out_file)$(daymic_lib)
.PHONY:all
all:
gcc ${file_1} ${file_2} -fPIC -shared -o $(out_so_name)
gcc ${main_file} -o ${out_file} -L. -l${out_file}
注意:
生成的 xx.so文件要添加他的路径,否则加载不上
用 export LD_LIBRARY_PATH=./ 或者在 /etc/ld.so.conf中加入xxx.so所在的目录,然后/sbin/ldconfig –v更新一下配置即可。
Makfile中两个变量引用 ${xx_1}${xx_2},在 xx_1后面一定不要有空格,否则引用变量的时候会把该空格引入其中,但是做这个例子的时候就遇到过这个问题,后来查询半天才发现,希望引以为戒。