简体   繁体   English

用C ++编写单元测试的Makefile

[英]Makefile for Unit Tests in C++

I'm struggling to write Makefiles that properly build my unit tests. 我正在努力编写正确构建单元测试的Makefile。 As an example, suppose the file structure looks like this 例如,假设文件结构如下所示

src/foo.cpp
src/foo.hpp
src/main.cpp
tests/test_foo.cpp
tests/test_all.cpp

So, to build the executable test_all, I'd need to build test_foo.o which in turn depends on test_foo.cpp but also on src/foo.o. 因此,要构建可执行文件test_all,我需要构建test_foo.o,而test_foo.o依赖于test_foo.cpp,但也依赖于src / foo.o。

What is the best practice in this case? 在这种情况下,最佳做法是什么? One Makefile in the parent folder? 父文件夹中有一个Makefile? One Makefile per folder? 每个文件夹一个Makefile? If so, how do I manage the dependencies across folders? 如果是这样,我如何管理文件夹之间的依赖关系?

Common practice is a Makefile per directory. 通常的做法是每个目录的Makefile。 That's what I would have suggested before I read "Recursive Make Considered Harmfull" ( http://miller.emu.id.au/pmiller/books/rmch/ ). 这就是我在阅读“Recursive Make Considered Harmfull”之前所建议的内容( http://miller.emu.id.au/pmiller/books/rmch/ )。 Now I'd recommend one Makefile. 现在我推荐一个Makefile。 Also check out the automatic dependency generation - now you don't even need to work out what your tests depends on. 还要检查自动依赖关系生成 - 现在您甚至不需要计算出测试所依赖的内容。 All you need is some targets. 你需要的只是一些目标。

The common practice is one Makefile for each folder. 通常的做法是为每个文件夹创建一个Makefile。 Here is a simple Makefile.am script for the root folder: 这是根文件夹的简单Makefile.am脚本:

#SUBDIRS = src tests
all:
    make -C ./src
    make -C ./tests    
install:
    make -C ./src install
uninstall:
    make -C ./src uninstall
clean:
    make -C ./src clean
test:
    make -C ./tests test

The corresponding Makefile.am for the src folder will look like this: src文件夹的相应Makefile.am将如下所示:

AM_CPPFLAGS = -I./

bin_PROGRAMS = progName

progName_SOURCES = foo.cpp main.cpp
LDADD = lib-to-link

progName_LDADD = ../libs/

Makefile.am for tests will look similar: Makefile.am 测试看起来类似:

AM_CPPFLAGS = -I../src

bin_PROGRAMS = tests

tests_SOURCES = test_foo.cpp test_all.cpp

Use automake to generate Makefile.in files from the .am files. 使用automake从.am文件生成Makefile.in文件。 The configure script will use the .in files to produce the Makefiles. configure脚本将使用.in文件生成Makefile。 (For small projects you would like to directly hand-code the Makefiles). (对于您希望直接手动编码Makefile的小项目)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM