CMake share library with multiple executables

When you setup your build environment, you should put some thought into the following three topics (beside others, but for this discussion/answer I reduced it to the three I feel are relevant here): Dependecies / Coupling Deployment Teams “Strong Coupling” I came to think of the add_subdirectory() command as supporting “strong coupling” and your current … Read more

Find package Eigen3 for CMake

Since Eigen3 is completely header only, all you ever need is the path to the include directory. And this one, you are already defining manually anyway. So there is no real need for a FindEigen3.cmake or FIND_PACKAGE call. Simply use INCLUDE_DIRECTORIES ( “$ENV{EIGEN3_INCLUDE_DIR}” ) or SET( EIGEN3_INCLUDE_DIR “$ENV{EIGEN3_INCLUDE_DIR}” ) IF( NOT EIGEN3_INCLUDE_DIR ) MESSAGE( FATAL_ERROR … Read more

Compile with /MT instead of /MD using CMake

You can modify the CMAKE_CXX_FLAGS_<Build Type> and/or CMAKE_C_FLAGS_<Build Type> variables: set(CMAKE_CXX_FLAGS_RELEASE “${CMAKE_CXX_FLAGS_RELEASE} /MT”) set(CMAKE_CXX_FLAGS_DEBUG “${CMAKE_CXX_FLAGS_DEBUG} /MTd”) If your CMake flags already contain /MD, you can ensure that the above commands are executed after the point at which /MD is inserted (the later addition of /MT overrides the conflicting existing option), or you can set the … Read more

How to set linker flags for OpenMP in CMake’s try_compile function

CMake has a standard module for testing if the compiler supports OpenMP: find_package(OpenMP) if (OPENMP_FOUND) set (CMAKE_C_FLAGS “${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}”) set (CMAKE_CXX_FLAGS “${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}”) set (CMAKE_EXE_LINKER_FLAGS “${CMAKE_EXE_LINKER_FLAGS} ${OpenMP_EXE_LINKER_FLAGS}”) endif() Note: This answer is not recommended to be used anymore for including OpenMP in the project for current CMake versions. Refer to the other answers.

How to set warning level in CMake?

In modern CMake, the following works well: if(MSVC) target_compile_options(${TARGET_NAME} PRIVATE /W4 /WX) else() target_compile_options(${TARGET_NAME} PRIVATE -Wall -Wextra -Wpedantic -Werror) endif() My colleague suggested an alternative version: target_compile_options(${TARGET_NAME} PRIVATE $<$<CXX_COMPILER_ID:MSVC>:/W4 /WX> $<$<NOT:$<CXX_COMPILER_ID:MSVC>>:-Wall -Wextra -Wpedantic -Werror> ) Replace ${TARGET_NAME} with the actual target name. -Werror is optional, it turns all warnings into errors. Or use add_compile_options(…) if … Read more