使用Makefile在子目录中生成目标文件 [英] Generate object files in subdirectory using a Makefile

查看:116
本文介绍了使用Makefile在子目录中生成目标文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个Makefile,以便在子目录中生成目标文件,而不是将它们放到src/文件夹中. 这是项目的结构:

I am trying to create a Makefile in order to generate object files in a subdirectory rather than let them in the src/ folder. Here is the structure of the project:

Trunk
- Server
  - src/
  - include/
- Common
  - src/
  - include/

Makefile位于Trunk/Server中.源文件位于Server/srcCommon/src中,因此Makefile当前具有以下内容:

The Makefile is located in Trunk/Server. Source files are located both in Server/src and Common/src, so the Makefile currently has something like this:

SRC        =        src/main.cpp                  \
                    src/Network.cpp               \
                    ../Common/src/SQLManager.cpp  \
                    ../Common/src/Utils.cpp

我想将生成的目标文件放在相应的obj文件夹中,因此Trunk/Server/objTrunk/Common/obj.我怎样才能做到这一点?我已经找到了许多在子目录(vpathpatsubst等)中生成目标文件的方法,但是我无法使其中任何一种都能用于此文件夹组织.

I woud like to put generated object files in respective obj folders, so Trunk/Server/obj and Trunk/Common/obj. How can I achieve this? I've found many ways to generate object files in subdirectories (vpath, patsubst and many more) but I can't make any of them work for this folder organization.

如果有一种方法可以将所有目标文件都放在Server/obj/中,那也是可以的.

If there is a way to put all object files in Server/obj/, that would be ok too.

这是完整的Makefile(减去一些源文件和链接的库): Edit2:更新了Didier Trosset的更改

Here's the complete Makefile (minus some source files and linked libraries): Updated with Didier Trosset's changes

CXX             =       g++

RM              =       rm -vf

NAME            =       Server

SRC             =       src/main.cpp                  \
                        src/Network.cpp               \
                        ../Common/src/SQLManager.cpp  \
                        ../Common/src/Utils.cpp

OBJ             =       $(subst src/,obj/, $(subst .cpp,.o, $(SRC)))

LDFLAGS         =       -lpthread -lm

CPPFLAGS        =       -std=c++0x -pedantic -Wextra -Wall -Wconversion -Iinclude -I../Common/include

all: Server

%.o: %.cpp
        $(CXX) $< -o $@

Server: $(OBJ)
        $(CXX) -o $(NAME) $(OBJ) $(LDFLAGS)

clean:
        $(RM) $(OBJ) *~

fclean: clean
        $(RM) $(NAME)

re: fclean Server

.PHONY: all clean fclean Server

推荐答案

鉴于这些定义,应使用subst代替目录的src部分和文件扩展名.

Given these definitions, subst should be used to substitute the src part of the directory, and the file extension.

OBJ = $(subst src/,bin/,$(subst .cpp,.o,$(SRC)))

然后,您必须添加新的模式规则来编译源文件. (您必须在源文件所在的每个目录中编写一个模式规则.)

Then, you have to add new pattern rules to compile your source files. (You have to write one pattern rule per directory where your source files are.)

obj/%.o: src/%.cpp
         $(CXX) -c $< -o $@

../Common/obj/%.o: ../Common/src/%.cpp
         $(CXX) -c $< -o $@

这篇关于使用Makefile在子目录中生成目标文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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