您好我需要为一个目录中的2个独立的cpp程序创建一个makefile。我有这个代码,但它无法正常工作。 .o文件无法创建。谢谢
OBJS = a b
EXEC = first_run second_run
#------ constant definitions
ALL_OBJ = $(OBJS:%=%.o)
all: $(EXEC)
clean:
$(RM) $(EXEC) $(OBJS) $(ALL_OBJ); make all
CC = g++
DO_OBJS = $(CC) -cpp -o $@.o $@.cpp; touch $@
DO_EXEC = $(CC) -s -o $@ $(ALL_OBJ)
#------ now compile
$(OBJS): $(@:%=%.o)
$(DO_OBJS)
$(EXEC): $(OBJS)
$(DO_EXEC)
答案 0 :(得分:3)
您的文件存在一些问题,但主要问题似乎是您尝试将两个源文件链接到单个可执行文件。您必须自己列出每个程序及其依赖项。
尝试使用这个简单的Makefile:
SOURCES = a.cpp b.cpp
OBJECTS = $(SOURCES:%.cpp=%.o)
TARGETS = first_run second_run
LD = g++
CXX = g++
CXXFLAGS = -Wall
all: $(TARGETS)
# Special rule that tells `make` that the `clean` target isn't really
# a file that can be made
.PHONY: clean
clean:
-rm -f $(OBJECTS)
-rm -f $(TARGETS)
# The target `first_run` depends on the `a.o` object file
# It's this rule that links the first program
first_run: a.o
$(LD) -o $@ $<
# The target `second_run` depends on the `b.o` object file
# It's this rule that links the second program
second_run: b.o
$(LD) -o $@ $<
# Tells `make` that each file ending in `.o` depends on a similar
# named file but ending in `.cpp`
# It's this rule that makes the object files
.o.cpp:
答案 1 :(得分:2)
KISS:
all: first_run second_run
clean:
rm -f first_run second_run
first_run: a.c
$(LINK.cc) $^ $(LOADLIBES) $(LDLIBS) -o $@
second_run: b.c
$(LINK.cc) $^ $(LOADLIBES) $(LDLIBS) -o $@
答案 2 :(得分:0)
我建议使用Makefile:
EXEC = first_run second_run
OBJS_FIRST = a.o
OBJS_SECOND = b.o
all: $(EXEC)
first_run: $(OBJS_FIRST)
$(CXX) -o $@ $(OBJS_FIRST)
second_run: $(OBJS_SECOND)
$(CXX) -o $@ $(OBJS_SECOND)
您不需要定义对象构建,因为make已经知道,如何做到这一点。