linux 动态链接库so的封装及调用

本文详细介绍如何使用C语言创建动态链接库(.so文件),包括hello.c和hello.h的定义,通过gcc编译生成动态链接库libmyhello.so,以及如何在test.c和main.c中调用该库。同时,探讨了当修改动态链接库中的全局变量或函数内容时,对于已编译的主程序的影响。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

       首先定义hello.c文件

#include <stdio.h>

void hello(const char * name)
{
        printf("Hello , %s!\n", name);
}

       定义hello.h头文件

#ifndef HELLO_H
#define HELLO_H

int g_count = 100;
void hello(const char* name);

#endif //HELLO_H

编译:

gcc -fPIC -c hello.c

gcc -shared -o libmyhello.so hello.o

或者:gcc -fPIC -shared -o libmyhello.so hello.c

拷贝libmyhello.so到/usr/lib/下或者使用 LD_LIBRARY_PATH=. ./XXX 指定链接位置。

        定义test.c文件

#include "hello.h"
void Test(const char * name)
{
        hello(name);
}

        定义test.h头文件

void Test(const char* name);

编译:

gcc -fPIC -c test.c

gcc -shared -o libtest.so test.o -L. -lmyhello

或者:gcc -fPIC -shared -o libmyhello.so test.c -L. -lmyhello

        定义main.c文件

#include "test.h"
#include "hello.h"
#include <stdio.h>

extern int g_count;
int main()
{
        Test("everyone");
        printf("count = %d\n", g_count);
        return 0;
}

编译:gcc -o main main.c -L. -lmyhello -ltest

执行main可执行程序,输出如下:

Hello , everyone!
count = 100
hello.h中全局变量g_count初始值改变后,编译libmyhello.so文件,不编译main.c文件,直接执行main不会有任何改变,只有重新编译main.c才能改变g_count输出值。

动态链接库修改函数中内容后编译,执行main则会发生改变。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值