My project directory looks like this:
/project
Makefile
/src
main.c
foo.c
bar.c
/exec
main
foo
bar
I want that the Makefile genrates an executable file for every .c
file in /src
folder and put the executable in /exec
folder.
It's my first time using Makefile, I tried the code below but it generates the exec files in the /src
folder and I want them to be in /exec
folder
CFLAGS := -Wall -g
SRC_DIR := src
EXEC_DIR := exec
SRC_FILES := $(wildcard $(SRC_DIR)/*.c)
all: $(SRC_FILES:.c=)
.c:
gcc $(CFLAGS) $< -o $(EXEC_DIR)/$@
CodePudding user response:
You need to take the different paths into account.
One possible solution is this:
CFLAGS := -Wall -g
SRC_DIR := src
EXEC_DIR := exec
SRC_FILES := $(wildcard $(SRC_DIR)/*.c)
all: $(SRC_FILES:$(SRC_DIR)/%.c=$(EXEC_DIR)/%)
$(EXEC_DIR)/%: $(SRC_DIR)/%.c
gcc $(CFLAGS) $< -o $@
Hints:
You can use make -n
to check which commands make would execute, but without actually executing them.
Also, its options -p
(print data base) and -d
(debug) are helpful to debug your Makefile.