[CMake] Adding compile and build type tests to CMake/CTest

Edward Diener eldlistmailingz at tropicsoft.com
Thu Sep 7 10:43:08 EDT 2017


On 9/7/2017 10:34 AM, paul via CMake wrote:
> On Thu, 2017-09-07 at 02:58 -0400, Edward Diener wrote:
>> On 9/6/2017 11:39 PM, P F via CMake wrote:
>>>
>>> The `add_test` function can run whatever command you want it to, including
>>> compiling a target:
>>>
>>> add_library(foo_compile_test STATIC EXCLUDE_FROM_ALL foo_compile_test.cpp)
>>> add_test(NAME foo_compile_test
>>>       COMMAND ${CMAKE_COMMAND} --build . --target foo_compile_test --config
>>> $<CONFIGURATION>
>>>       WORKING_DIRECTORY ${CMAKE_BINARY_DIR})
>>>
>>> Then you set cmake to expect failure:
>>>
>>> set_tests_properties(foo_compile_test PROPERTIES WILL_FAIL TRUE)
>>>
>>> You can also check for output instead of just expecting failure:
>>>
>>> set_tests_properties(mytest PROPERTIES
>>>     PASS_REGULAR_EXPRESSION "foo failed"
>>> )
>>>
>>> This is especially useful to make sure that the error is from the
>>> static_assert message and not from another compile error.
>>>
>>> Of course, cmake could provide a module which provides a function to do
>>> this, which additionally could help workaround the caveats of this
>>> approach. This is essentially what `bcm_test` in the boost cmake modules
>>> do. > > Hopefully, in the future this module could be merged upstream into
>>> cmake.
>> It seems like a hack to have to build a CMake target, with the
>> add_library call, just to compile a source file as a test.
> 
> 
> I dont see how this is a hack. Cmake is target-oriented, if I want to control
> the compile flags for this compile-test, I can do:
> 
> target_compile_options(foo_compile_test -Wall -Werror)
> 
> If it were builtin to cmake, how would the user set the compile options? It
> seems cmake would need to add `target_*` based function for compile tests as
> well. This seems bloated and inconsistent.

I meant it was a hack because you need to add a build of a STATIC 
library just to do a compile test. However if, as has been suggested, 
you can alternatively add a build of an OBJECT library to do the compile 
test, then that seems the correct way of doing it to me, if it actually 
works. I am surprised that it works, else I imagine `bcm_test` would 
have used that instead instead of building a STATIC library.



More information about the CMake mailing list