c++ - 使用 cmake : how could I write a test to verify that a class is abstract?

标签 c++ testing cmake automated-tests

我想知道我是否可以编写一个 .cpp 文件来尝试实例化一个抽象类:

// 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

然后让 cmake 尝试编译它。我在这里的意思是,我想证明该类是抽象的并且仍然是抽象的,因此永远无法实例化它。

我知道如何创建有效目标,但我想知道是否有办法为已知无效的目标运行 cmake?以前有人这样做过吗?


更新:

根据 steveire 的回答和下面的评论,我编写了自己的模块来完成工作并确保该类确实是抽象的(而不是指望任何编译器失败都表明是抽象类。)所以我们必须匹配特定错误的错误消息。我支持其中的 4 个,其中 2 个明确使类抽象(至少一个函数是纯虚拟的),另外 2 个将 protected 和私有(private)构造函数视为一种抽象类(就像抽象类一样,你不能做一个新的 <类名>.

您可以在 Snap 中找到该模块! C++ git 在这里:

https://sourceforge.net/p/snapcpp/code/ci/master/tree/snapCMakeModules/Modules/

它被命名为CheckCXXAbstractClass.cmake

最佳答案

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()

如果您适本地设置了 CMAKE_REQUIRED_INCLUDES 变量,您可以#include "A"

关于c++ - 使用 cmake : how could I write a test to verify that a class is abstract?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23977313/

相关文章:

c++ - 为什么 bool 看起来占用的内存和 int 一样多? C++

javascript - Mocha 只运行一个测试文件

compiler-errors - 使用 cmake 构建带有 cpp 和 cuda 源的 pybind11 模块

cmake - 使用 cmake 从复杂项目中仅安装一个目标(及其依赖项)(对更好的解决方案开放)

c++ - 如何判断传入的数组是一维、二维还是N维数组

c++ - 如何在 R 中使用 Rcpp 在 C++ 中进行数值积分

c++ - 删除重复链接列表

ruby-on-rails - Rails 和 MiniTest : add additional folder

testing - 是否可以在 testcafe E2E 测试中取消初始化/重新初始化/删除角色?

c++ - Cmake 未使用 "target_link_directory"正确添加目录