[CMake] Check whether C++ headers are self-sufficient
Roger Leigh
rleigh at codelibre.net
Wed Mar 25 10:44:44 EDT 2015
On Sat, Mar 14, 2015 at 01:19:21PM +0100, Christoph Grüninger wrote:
> Dear CMakers,
> I want to have all my C++ headers self-sufficient (self-contained),
> i.e., a header can be included without additional includes. This is not
> only handy but also part of Google's C++ styleguide [2].
>
> It would be great to have a make target (let's call it headercheck),
> that can check for this, by compiling a simple test.cc file for each
> current_header.h:
> #include <config.h>
> #include "current_header.h"
> #include "current_header.h"
>
> Additionally it would be great to have such a target for every folder
> (checking all headers recursively) and every header that is explicitly
> passed as an argument.
>
> We tried this with CMake: We generate a test.cc file per header and
> create a library for every cc file. The problem is, that we get hundreds
> of additional targets, we generate a lot of folders and files which can
> increase our build directory size by an order of magnitude and it does
> not work properly on a per file or per directory basis.
I've taken exactly your approach. However:
- I'm not testing the double include at present
- I generate a single target per library, collecting all the object files
into a single testcase
- I compile each header *twice*, so in addition to catching errors in the
include guards, I also catch errors where I might have accidentally
defined a global or static member in the header and this will trigger a
link error
For anyone two wants to reuse it:
https://github.com/openmicroscopy/bioformats/blob/develop/cpp/cmake/HeaderTest.cmake
(it uses gtest but that's easily excised if not required)
To use, in your source directory:
https://github.com/openmicroscopy/bioformats/blob/develop/cpp/lib/ome/bioformats/CMakeLists.txt#L182
header_include_list_write(STATIC_HEADERS_VAR GENERATED_HEADERS_VAR header-test-name dest-dir)
And in your test directory (if different)
https://github.com/openmicroscopy/bioformats/blob/develop/cpp/test/ome-bioformats/CMakeLists.txt#L45
header_test_from_file(bin-name library-name test-name)
While these were written for this particular project, if there's
interest in having a similar thing in cmake, I'd be happy to clean
it up and improve it for general use.
Kind regards,
Roger
--
.''`. Roger Leigh
: :' : Debian GNU/Linux http://people.debian.org/~rleigh/
`. `' schroot and sbuild http://alioth.debian.org/projects/buildd-tools
`- GPG Public Key F33D 281D 470A B443 6756 147C 07B3 C8BC 4083 E800
More information about the CMake
mailing list