Linux 静态库-动态库-Makefile管理开发实例

本文详细介绍在Linux环境下如何从零开始创建静态库和动态库,包括源文件编写、头文件定义、Makefile配置以及最终的主程序链接过程。通过具体实例,读者将学会如何组织项目结构,掌握静态库和动态库的开发流程。

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

程序结构

.
├── inc
│ ├── hello.h
│ └── world.h
├── liba
│ ├── hello.c
│ └── Makefile
├── libso
│ ├── Makefile
│ └── world.c
├── Makefile
└── src
├── main.c
└── Makefile

编写静态库和Makefile

编写hello.c

#include <stdio.h>
#include "hello.h"
void hello(void){
        printf("this is hello static lib\n");
}

编写hello.h

#ifndef _HELLO_H
#define _HELLO_H
extern void hello(void);
#endif

编写Makefile

SRC=$(wildcard *.c)
OBJ=$(patsubst %.c, %.o, $(SRC))
TAR=libhello.a
INC=../inc

all:$(TAR)

$(TAR):$(OBJ)
        $(AR) -rcs $@ $^

%.o:%.c
        $(CC) $(CFLAGS) -I$(INC) -o $@ -c $<

.PHONY:clean
clean:
        rm -rf *.a *.o

编写动态库和Makefile

编写world.c

#include <stdio.h>
#include "world.h"
void world(void){
        printf("this is world dynamic lib\n");
}

编写world.h

#ifndef _WORLD_H
#define _WORLD_H
extern void world(void);
#endif

编写Makefile

SRC=$(wildcard *.c)
OBJ=$(patsubst %.c, %.o, $(SRC))
TAR=libworld.so
INC=../inc

all:$(TAR)

$(TAR):$(OBJ)
        $(CC) $(CFLAGS) -I$(INC) -fpic -shared -o $@ $^

%.o:%.c
        $(CC) $(CFLAGS) -I$(INC) -fpic -shared -o $@ -c $<

.PHONY:clean
clean:
        rm -rf *.so *.o

编写主程序和Makefile

编写main.c

#include <stdio.h>
#include "hello.h"
#include "world.h"
void main(void){
        hello();
        world();
}

编写Makefile

SRC=$(wildcard *.c)
OBJ=$(patsubst %.c, %.o, $(SRC))
TAR=app
INC=../inc
LIBA=../liba
LIBSO=../libso

all:$(TAR)

$(TAR):$(OBJ)
        $(CC) $(CFALGS) -I$(INC) -o $@ $^ -L$(LIBA) -lhello -L$(LIBSO) -lworld

%.o:%.c
        $(CC) $(CFLAGS) -I$(INC) -o $@ -c $<

.PHONY: clean

clean:
        rm -rf $(TAR) *.o 

编写顶层Makefile

编写Makefile


all:
        make -C ./libso
        make -C ./liba
        make -C ./src
clean:
        make clean -C ./src
        make clean -C ./libso 
        make clean -C ./liba

.PHONY:all clean

设置动态库路径

export LD_LIBRARY_PATH=…/libso/:$LD_LIBRARY_PATH

执行结果

test@ubuntu:~/training/app/src$ ./app 
this is hello static lib
this is world dynamic lib
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值