将obj文件输出到Makefile中的obj目录

时间:2013-07-01 06:46:38

标签: makefile

您好我通过修改此示例编写了此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

2 个答案:

答案 0 :(得分:3)

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

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 $@ $<

答案 1 :(得分:0)

尝试使用以下内容:

OUT_DIR=obj
program_bare_OBJS := $(program_C_OBJS) $(program_CXX_OBJS)
program_OBJS=$(addprefix $(OUT_DIR)/,$(program_bare_OBJS))