0

嗨,我通过修改此示例编写了此 Makefile:https ://sites.google.com/site/michaelsafyan/software-engineering/how-to-write-a-makefile

program_NAME := bin/myprogram

SRC_DIR := src

#
#srces
#
program_C_SRCS := $(wildcard $(SRC_DIR)/*.c)
program_CXX_SRCS :=  $(wildcard $(SRC_DIR)/*.cpp)

#
#obj files
#
program_C_OBJS := ${program_C_SRCS:.c=.o}
program_CXX_OBJS := ${program_CXX_SRCS:.cpp=.o}
program_OBJS := $(program_C_OBJS) $(program_CXX_OBJS)

#
# include and library dirs; also libraries
#
program_INCLUDE_DIRS := inc
program_LIBRARY_DIRS :=
program_LIBRARIES :=

# flags
CPPFLAGS += $(foreach includedir,$(program_INCLUDE_DIRS),-I$(includedir))
LDFLAGS += $(foreach librarydir,$(program_LIBRARY_DIRS),-L$(librarydir))
LDFLAGS += $(foreach library,$(program_LIBRARIES),-l$(library))

#
# targets
#

.PHONY: all clean distclean

all: $(program_NAME)

$(program_NAME): $(program_OBJS)
       $(LINK.cc) $(program_OBJS) -o $(program_NAME)


clean:
   @- $(RM) $(program_NAME)
   @- $(RM) $(program_OBJS)

distclean: clean

它以下列方式工作。下面的类被编译成可执行的“myprogram”,在bin目录中输出。唯一的问题是目标文件是在src文件夹中创建的,而不是在obj文件夹中。如何修改此 makefile 以便obj在文件夹中创建obj文件?谢谢你。

 /project
        Makefile

        /src
            Class1.cpp
            Class2.cpp
            main.cpp
        /obj

        /bin
            myProgram
        /inc
            Class1.h
            Class2.h
4

2 回答 2

3

首先,您可以使用例如subst函数将源文件目录替换为目标文件目录:

program_OBJS  = $(subst $(SRC_DIR),$(OBJ_DIR),$(program_C_OBJS))
program_OBJS += $(subst $(SRC_DIR),$(OBJ_DIR),$(program_CXX_OBJS))

当然,您现在需要为创建目标文件添加一个目标,否则这些目标将不会放在正确的位置:

$(OBJ_DIR)/%.o: $(SRC_DIR)/%.c
    $(CC) $(CFLAGS) -c -o $@ $<

$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp
    $(CXX) $(CXXFLAGS) -c -o $@ $<
于 2013-07-01T06:56:35.387 回答
0

尝试类似:

OUT_DIR=obj
program_bare_OBJS := $(program_C_OBJS) $(program_CXX_OBJS)
program_OBJS=$(addprefix $(OUT_DIR)/,$(program_bare_OBJS))
于 2013-07-01T06:53:22.030 回答