经过一番搜索后,我设法将以下Makefile放在一起:
CC = gcc
CFLAGS = -c -Wall
LDFLAGS =
SOURCEFILES = main.c
SOURCES = src/$(SOURCEFILES)
OBJECTS = $(SOURCES:.c=.o)
EXECUTABLE = netsim
all: $(SOURCES) $(EXECUTABLE)
$(EXECUTABLE): $(OBJECTS)
$(CC) $(LDFLAGS) $(OBJECTS) -o $@
.c.o:
$(CC) $(CFLAGS) $< -o $@
clean:
rm -rf netsim $(OBJECTS)
我希望能够将我的目标文件移动到另一个目录中,但一直在努力使其工作。我错过了什么?
答案 0 :(得分:6)
诀窍是不要移动你的物体 您应构建并在构建它们的地方使用它。
例如,您具有以下目录结构:
$ tree .
├── Makefile
├── include
│ └── common_head.h
├── obj
└── src
├── foo.c
└── main.c
手动执行:
$ gcc -o ./obj/foo.o -c ./src/foo.c -I ./include # Build Object #
$ gcc -o ./obj/main.o -c ./src/main.c -I ./include
$ gcc -o exe ./obj/foo.o ./obj/main.o # Build Executable #
Makefile来模拟上面的
C_FLAGS := -g -Wall -Wextra
CC := gcc
RM := rm
LINKFLAGS := -lanylibrary
.PHONY: $(TARGET)
.PHONY: clean
VPATH:= ./src/ ./obj/ ./include/
# Path for .c , .h and .o Files
SRC_PATH := ./src/
OBJ_PATH := ./obj/
INC_PATH := -I ./include
# Executable Name
TARGET := exe
# Files to compile
OBJ1 := foo.o \
main.o
OBJ := $(patsubst %,$(OBJ_PATH)%,$(OBJ1))
# Build .o first
$(OBJ_PATH)%.o: $(SRC_PATH)%.c
@echo [CC] $<
@$(CC) $(C_FLAGS) -o $@ -c $< $(INC_PATH)
# Build final Binary
$(TARGET): $(OBJ)
@echo [INFO] Creating Binary Executable [$(TARGET)]
@$(CC) -o $@ $^ $(LINKFLAGS)
# Clean all the object files and the binary
clean:
@echo "[Cleaning]"
@$(RM) -rfv $(OBJ_PATH)*
@$(RM) -rfv $(TARGET)
所以当你做一个Make
$ make -B
[CC] src/foo.c
[CC] src/main.c
[INFO] Creating Binary Executable [exe]
要查看干运行使用make -n
$ make clean ; make -n
g++ -g -Wall -Wextra -o obj/foo.o -c src/foo.c -I ./include
g++ -g -Wall -Wextra -o obj/main.o -c src/main.c -I ./include
g++ -o exe obj/foo.o obj/main.o -lanylibrary
因此,在构建目录结构后,应该如下所示。
$ tree .
├── Makefile
├── exe
├── include
│ └── common_head.h
├── obj
│ ├── foo.o
│ └── main.o
└── src
├── foo.c
└── main.c
从我之前的回答开始。
您不必使用任何PHONY move
,也不会不必要地重新创建任何对象。
答案 1 :(得分:0)
这样的东西?
SOURCES = src/main.c
OBJECTS = obj/main.o
...
obj/%.o: src/%.c
$(CC) $(CFLAGS) $< -o $@
一旦有效,你可以添加更多技巧,例如:
OBJECTS = $(patsubst src/%.c, obj/%.o, $(SOURCES)