Issue
I'm trying to compile the following file, into two different executables, using CMakeLists.txt.
This file is: main.cpp
#include <iostream>
#include <cassert>
int main(int, char**) {
std::cout << "Hello, world!\n";
assert(0);
return 0;
}
and this is the CMakeLists.txt
file
cmake_minimum_required(VERSION 3.0.0)
project(multi_Tar VERSION 0.1.0)
SET(CMAKE_CXX_FLAGS "-O3 -DNDEBUG")
SET(CMAKE_CXX_FLAGS_RELEASE "-O0")
add_executable(multi_Tar main.cpp)
add_executable(tests main.cpp)
set_target_properties(tests PROPERTIES COMPILE_FLAGS "${CMAKE_CXX_FLAGS_RELEASE}")
This solution does not work. When I run ./tests
I'm not getting an assertion error.
The motivation is using the same CMakeLists.txt
for testing validity, and to benchmark the same code.
Thanks for the help.
Edit after @squareskittles answer:
Thanks for the answer!
(Including the code for the answer:)
cmake_minimum_required(VERSION 3.0.0)
project(multi_Tar VERSION 0.1.0)
add_executable(multi_Tar main.cpp)
# Add the compile options for multi_Tar.
target_compile_definitions(multi_Tar PRIVATE -O3 -DNDEBUG)
add_executable(tests main.cpp)
# Add the compile options for tests.
target_compile_definitions(multi_Tar PRIVATE -O0)
I tried using your solution, but I got the following error:
<command-line>: error: macro names must be identifiers
<command-line>: error: macro names must be identifiers
CMakeFiles/multi_Tar.dir/build.make:62: recipe for target 'CMakeFiles/multi_Tar.dir/main.cpp.o' failed
make[2]: *** [CMakeFiles/multi_Tar.dir/main.cpp.o] Error 1
CMakeFiles/Makefile2:104: recipe for target 'CMakeFiles/multi_Tar.dir/all' failed
make[1]: *** [CMakeFiles/multi_Tar.dir/all] Error 2
Makefile:105: recipe for target 'all' failed
make: *** [all] Error 2
I tried changing the CMakeLists.txt
a bit, but did not manage to get it to work.
Also, should the last line in your solution be:
target_compile_definitions(multi_Tar PRIVATE -O0)
or
target_compile_definitions(tests PRIVATE -O0)
Solution
Based on the CMake code, the tests
executable should not produce an assertion error. You added the NDEBUG
compile definition, which disables the assert
macro per the assert
documentation.
If you want to apply compile flags to specific CMake targets, you should use the target-specific CMake commands, such as target_compile_options
and target_compile_definitions
. I'm not sure where you found this CMake code, but manually modifying the CMAKE_CXX_FLAGS*
variables is discouraged and typically unnecessary, especially in more recent versions of CMake.
Try something like this instead, to apply the NDEBUG
flag only to the multi_Tar
target:
cmake_minimum_required(VERSION 3.0.0)
project(multi_Tar VERSION 0.1.0)
add_executable(multi_Tar main.cpp)
# Add the compile options for multi_Tar.
target_compile_options(multi_Tar PRIVATE -O3 -DNDEBUG)
add_executable(tests main.cpp)
# Add the compile options for tests.
target_compile_options(tests PRIVATE -O0)
Answered By - squareskittles