如何在应该失败的CMake中实现编译测试

How to implement compilation test in CMake which should fail?

本文关键字:CMake 实现 编译 测试 失败      更新时间:2023-10-16

我正在研究一个长整数库作为我C++家庭作业,我们的老师提供了其接口使用的示例。这是此文件的一部分:

void test_conversions() 
{ 
  int ordinary = 42; 
  lint long_int(ordinary); 
  long_int = ordinary; 
  ordinary = static_cast<int>(long_int); // ok 
  std::string s("-15"); 
  lint z(s); 
  z.to_string() == s; // this should be true
} 
void failed_conversions_test() 
{
  int ordinary = 42; 
  std::string str = "-42"; 
  lint x = 5; 
  ordinary = x; // must be compilation error! 
  x = str; // must be compilation error! 
  str = x; // must be compilation error! 
}

我想在构建过程中测试此文件的兼容性。如您所见,应该有四个测试:一个用于编译成功(test_conversions),三个用于failed_conversions_test中呈现的每个失败。我可以通过添加存根int main()并在CMakeLists.txt中调用ADD_TEST来轻松实现编译成功检查,但是如何告诉CMake编译其余三个测试并确保编译不成功?

我正在考虑添加类似"运行执行所有操作的自定义脚本"之类的内容,但这非常依赖于编译器和平台,看起来不是好方法。

谢谢。

try_compile 命令可能是您要查找的。

您可以使用它来尝试构建单个源文件,并将结果报告回 CMake:

try_compile(COMPILE_SUCCEEDED ${CMAKE_BINARY_DIR}/compile_tests my_test_src.cpp)
if(COMPILE_SUCCEEDED)
  message("Success!")
endif()

此功能背后的动机是测试编译器功能,因此它只会在 CMake 配置时执行,而不是在构建时执行。如果您仍然想要后者,则需要求助于带有脚本的自定义构建步骤。