With cmake: how could I write a test to verify that a class is abstract?

automated-tests, c++, cmake, testing

Solution

http://www.cmake.org/cmake/help/v3.0/command/try_compile.html

http://www.cmake.org/cmake/help/v3.0/module/CheckCXXSourceCompiles.html

check_cxx_source_compiles(
    "class A { void foo() = 0; };\nint main() { new A; }"
    BUILT_ABSTRACT
)
if (BUILT_ABSTRACT)
    message(FATAL_ERROR "A can be instantiated, but should be abstract.")
endif()

You can `#include "A"` if you set the `CMAKE_REQUIRED_INCLUDES` variable appropriately.

Problem

I'm wondering whether I could write a .cpp file that attempts to instantiate an abstract class: ``` // file: test_ensure_A_is_abstract.cpp class A { void foo() = 0; }; int main() { new A; } // a simple shell script would look like this, but that is missing all the // options cmake normally generates (-I, -g, -c, -o, ...) if g++ test_ensure_A_is_abstract.cpp; then exit 1; else exit 0; fi ``` and then have cmake try to compile it. My point here is that I want to prove that the class is and remains abstract so one cannot ever instantiate it. I know how to create a valid target, but I am wondering whether there would be a way to run cmake for a target known to be invalid? Anyone has done that before? Update: As per steveire answer and comments below, I wrote my own module to do the work and make sure that the class is really abstract (instead of counting on any compiler failure as indication of an abstract class.) So we have to have an error message that match a specific error. I support 4 of them, 2 that clearly make the class abstract (at least one function is pure virtual) and another 2 which view protected and private constructors as making a kind of abstract class (just like abstract classes, you cannot do a new <class name>. You can find that module in the Snap! C++ git here: https://sourceforge.net/p/snapcpp/code/ci/master/tree/snapCMakeModules/Modules/ It is named CheckCXXAbstractClass.cmake.

Original source