yeputons
yeputons

Reputation: 9238

How to implement compilation test in CMake which should fail?

I'm working on a long integers library as my C++ home assignment and our teacher has provided as an example of its interface usage. Here is a part of this file:

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! 
}

I want to test this file for compilatibility during building process. As you can see, there should be four tests: one for compilation success (test_conversions) and three for each of fails presented in failed_conversions_test. I can easily implement compilation success check by adding a stub int main() and calling ADD_TEST in CMakeLists.txt, but how do I tell CMake to compile the remaining three tests and ensure that compilation was unsuccessful?

I was thinking about adding something like 'run custom script which do all the things', but this is very compiler- and platform- dependent and doesn't look like the good way.

Thank you.

Upvotes: 4

Views: 1820

Answers (1)

ComicSansMS
ComicSansMS

Reputation: 54589

The try_compile command might be what you are looking for.

You can use it to try building a single source file and have the result reported back to CMake:

try_compile(COMPILE_SUCCEEDED ${CMAKE_BINARY_DIR}/compile_tests my_test_src.cpp)

if(COMPILE_SUCCEEDED)
  message("Success!")
endif()

The motivation behind this feature was to test for compiler features, so it is only going to be executed at CMake configure time, not at build time. If you still want the latter, you need to resort to a custom build step with a script.

Upvotes: 5

Related Questions