将obj文件输出到Makefile中的obj目录 [英] Outputting obj files to obj directory in Makefile

查看:728
本文介绍了将obj文件输出到Makefile中的obj目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我通过修改以下示例来编写此Makefile:

Hi I wrote this Makefile by modifying this example: 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文件?谢谢.

It works in the following way. The classes below are compiled into an executable "myprogram" which is output in the bin directory. The only issue is the object files are created inside the src folder, instead of the obj folder. How can I modify this makefile such that obj files are created in the obj folder? Thank you.

 /project
        Makefile

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

        /bin
            myProgram
        /inc
            Class1.h
            Class2.h

推荐答案

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

To start with, you could use e.g. the subst function to replace the source-file directory with the object-file directory:

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

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

Of course you now need to add a target for object-file creation, as these will not be put in the correct place otherwise:

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

$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp
    $(CXX) $(CXXFLAGS) -c -o $@ $<

这篇关于将obj文件输出到Makefile中的obj目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆