linux 下生成动态库.so并引用

动态库的引入及减少了主代码文件的大小,同时生成的动态库又是动态加载的,只有运行的时候才去加载,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后面一定不要有空格,否则引用变量的时候会把该空格引入其中,但是做这个例子的时候就遇到过这个问题,后来查询半天才发现,希望引以为戒。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值