Suppose we have client-server application, compiling by one makefile. Server uses libtask for parallel clients serving. Client uses ncurses for some graphic.
directory tree looks like this:
./
--bin/
--obj/
--src/
----client/*.c
----server/*.c
--makefile
So, here is makefile. Can we simplify it? I read some related questions on stackoverflow and I think it almost ideal, except of linking binaries, when we can see repeated commands. Some suggestions for style/cross-platform working will be useful. Thank you!
.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)
You’re probably more general than you need to be: For example, I wouldn’t make the directories configurable – that only makes sense for destinations of an
installtarget.Anyway, this is how I would write your makefile (untested):