gpt4 book ai didi

c - makefile 简化

转载 作者:行者123 更新时间:2023-11-30 18:00:55 28 4
gpt4 key购买 nike

假设我们有客户端-服务器应用程序,由一个 makefile 编译。服务器使用 libtask 为并行客户端提供服务。客户端使用 ncurses 来处理某些图形。目录树如下所示:

./
--bin/
--obj/
--src/
----client/*.c
----server/*.c
--makefile

所以,这是 makefile。我们可以简化一下吗?我在 stackoverflow 上读到了一些相关问题,我认为这几乎是理想的,除了链接二进制文件之外,当我们可以看到重复的命令时。一些关于风格/跨平台工作的建议将会很有用。谢谢!

.PHONY: all clean

TASKLIB = -ltask
CURSESLIB = -lncurses
CFLAGS = -Wall -Werror -pedantic

bin = server client
obj_dir = obj
bin_dir = bin
ssource := src/server
csource := src/client
search_wildcard s := $(addsuffix /*.c, $(ssource))
search_wildcard c := $(addsuffix /*.c, $(csource))
sobjs = $(addprefix $(obj_dir)/, $(patsubst %.c, %.o, $(notdir $(wildcard $(search_wildcard s)))))
cobjs = $(addprefix $(obj_dir)/, $(patsubst %.c, %.o, $(notdir $(wildcard $(search_wildcard c)))))

all: $(bin)
@echo "done!"

server: CFLAGS+=$(TASKLIB)
client: CFLAGS+=$(CURSESLIB)

clean:
rm $(sobjs) $(cobjs) $(obj_dir)/*.d $(bin_dir)/client $(bin_dir)/server

VPATH := $(ssource) $(csource)

server: $(sobjs)
@test -d $(bin_dir) || mkdir $(bin_dir)
@echo "Linking $(@F)..."
@$(CC) $< $(CFLAGS) -o $(bin_dir)/$@

client: $(cobjs)
@test -d $(bin_dir) || mkdir $(bin_dir)
@echo "Linking $(@F)..."
@$(CC) $< $(CFLAGS) -o $(bin_dir)/$@

$(obj_dir)/%.o: %.c
@test -d $(obj_dir) || mkdir $(obj_dir)
@echo "Compiling $(@F)..."
@$(CC) $< $(CFLAGS) -c -MD -o $@

include $(wildcard $(obj_dir)/*.d)

最佳答案

您可能比您需要的更笼统:例如,我不会使目录可配置 - 这只对安装目标的目的地有意义。

无论如何,这就是我编写你的 makefile 的方式(未经测试):

CFLAGS := -Wall -Werror -pedantic
RM := rm -f
MKDIR := mkdir -p

BINARIES := bin/server bin/client
SERVER_OBJECTS := $(patsubst src/%.c, obj/%.o, $(wildcard src/server/*.c))
CLIENT_OBJECTS := $(patsubst src/%.c, obj/%.o, $(wildcard src/client/*.c))
OBJECTS := $(SERVER_OBJECTS) $(CLIENT_OBJECTS)

.PHONY : build clean realclean

build : $(BINARIES)

clean :
$(RM) $(OBJECTS) $(OBJECTS:%.o=%.d)

realclean : clean
$(RM) $(BINARIES)

bin/server : LDLIBS := -ltask
bin/client : LDLIBS := -lncurses

bin/server : $(SERVER_OBJECTS)
bin/client : $(CLIENT_OBJECTS)

$(BINARIES) :
@$(MKDIR) $(dir $@)
$(CC) $(CFLAGS) -o $@ $^ $(LDLIBS)

include $(wildcard obj/*.d)

$(OBJECTS) : obj/%.o : src/%.c
@$(MKDIR) $(dir $@)
$(CC) $(CFLAGS) -c -MD -o $@ $<

关于c - makefile 简化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10130409/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com