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

程序结构

.
├── 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

猜你喜欢

转载自blog.csdn.net/taoxp123456/article/details/88054327
今日推荐