0

您好,我需要为一个目录中的 2 个单独的 cpp 程序创建一个生成文件。我有这个代码,但它不能正常工作。.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)
4

3 回答 3

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:
于 2012-10-15T19:14:50.520 回答
2

吻:

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 $@
于 2012-10-15T19:16:45.457 回答
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 已经知道如何做到这一点。

于 2012-10-15T19:16:32.483 回答