Makefile将来自不同目录的源文件的对象文件放入一个单独的目录中? [英] Makefile to put object files from source files different directories into a single, separate directory?
问题描述
我使用UnitTest ++来允许我为一些C ++代码创建单元测试(应该在Linux或Mac OS X上构建)。我有一个这样的目录结构:
I'm using UnitTest++ to allow me to create unit tests for some C++ code (that should build on Linux or Mac OS X). I have a directory structure like this:
src
- Foo.cpp
- Bar.cpp
test
- FooTest.cpp
- BarTest.cpp
- Main.cpp
- Makefile
UnitTest++
- libUnitTest++.a
$ b
And this Makefile (adapted from the UnitTest++ Makefile) works nicely (with GNU make):
test = TestFooAndBar
src = ../src/Foo.cpp \
../src/Bar.cpp
test_src = Main.cpp \
FooTest.cpp \
BarTest.cpp
lib = ../UnitTest++/libUnitTest++.a
objects = $(patsubst %.cpp,%.o,$(src))
test_objects = $(patsubst %.cpp,%.o,$(test_src))
.PHONY: all
all: $(test)
@echo Running unit tests...
@./$(test)
$(test): $(lib) $(test_objects) $(objects)
@echo Linking $(test)...
@$(CXX) $(LDFLAGS) -o $(test) $(test_objects) $(objects) $(lib)
.PHONY: clean
clean:
-@$(RM) -f $(objects) $(test_objects) $(test) 2> /dev/null
%.o : %.cpp
@echo $<
@$(CXX) $(CXXFLAGS) -c $< -o $(patsubst %.cpp,%.o,$<)
但是我想将所有.o文件放在test目录的obj子目录中。我如何修改这个Makefile?
But I want to put all the .o files in an "obj" subdirectory of the "test" directory. How do I modify this Makefile to do so?
我已经尝试向对象和test_objects变量添加obj /,但是我无法弄清楚如何修改%.o规则,以便它知道.o文件在哪里,并引用正确的.cpp文件。是否需要创建两个独立的规则,每个.cpp文件集合一个?
I've tried adding "obj/" to the objects and test_objects variables, but I can't figure out how to modify the %.o rule so it knows where the .o files are and refers to the correct .cpp files. Do I need to create two separate rules, one for each set of .cpp files?
如果不是定义src和test_src变量,那将会更简单,我只需要Makefile为所有.cpp文件(在与Makefile和../ src /相同的目录中)构建一个.o(到obj /)?
Would it be simpler if instead of defining the src and test_src variables, I just have the Makefile build a .o (into obj/) for all .cpp files (both in the same directory as the Makefile and in ../src/)?
推荐答案
有多种方法可以做到,但这是一个很好的方法(我真的应该有这个热键)。
There's more than one way to do it, but this is a pretty good one (I really should have that hotkeyed).
vpath %.cpp ../src
src = Foo.cpp Bar.cpp
test_src = Main.cpp FooTest.cpp BarTest.cpp
objects = $(patsubst %.cpp,obj/%.o,$(src))
test_objects = $(patsubst %.cpp,obj/%.o,$(test_src))
$(objects): | obj
obj:
@mkdir -p $@
obj/%.o : %.cpp
@echo $<
@$(CXX) $(CXXFLAGS) -c $< -o $@
这篇关于Makefile将来自不同目录的源文件的对象文件放入一个单独的目录中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!