'How do you set compile flags in CMake?
I'm writing a project using the Slate linear algebra library in C++, with MKL, MPI and OpenMP as dependencies. Usually, I run my program on a Linux based system with
$ mpicxx -fopenmp -Wall -std=c++17 -MMD -I/opt/slate/include -DSLATE_NO_CUDA -c -o test.o test.cpp
$ mpicxx -o test test.o -fopenmp -L/opt/slate/lib -Wl,-rpath,/opt/slate/lib -lslate -lblaspp -llapackpp
However, recently I wanted to try out CMake, but I can't get it to work correctly.
cmake_minimum_required(VERSION 3.12)
# set the project name and version
project(1D_DFT VERSION 0.1)
#Slate directories
set(slate_dir /opt/slate)
#Compiler and libraries
set(CXXFLAGS -fopenmp -Wall -std=c++17 -MMD -I${slate_dir}/include -DSLATE_NO_CUDA)
set(LDFLAGS -fopenmp -L${slate_dir}/lib -Wl,-rpath,${slate_dir}/lib)
set(LIBS -lslate -lblaspp -llapackpp)
#Setting compiler
set(CMAKE_CXX_FLAGS ${CXXFLAGS})
set(CMAKE_EXE_LINKER_FLAGS ${LDFLAGS} ${LIBS})
add_library(test.o OBJECT test.cpp)
#Add the executable
add_executable(1D_DFT $<TARGET_OBJECTS:test.o>)
SET_SOURCE_FILES_PROPERTIES(
$<TARGET_OBJECTS:test.o>
PROPERTIES
GENERATED true
It doesn't recognise any of the compiler or linker flags! How does one tell CMake to run with a specific set of flags?
Solution 1:[1]
As pointed out by LHLaurini in the comments, you should use quotes around the flags when assigning them to variables. If you don't, CMake will turn them into a semicolon-delimited list and mess up the commands. Here's an example of how to do it correctly:
set(CXXFLAGS "-fopenmp -Wall -std=c++17 -MMD -I${slate_dir}/include -DSLATE_NO_CUDA")
set(CMAKE_CXX_FLAGS "${CXXFLAGS}")
More importantly, however, writing CMake files involves a very different paradigm from writing Makefiles. Modern best practices would recommend setting flags and libraries as properties of specific targets. Here's a presentation I would recommend to learn more about this paradigm. If you apply these design principles to your CMake code, it comes out looking more like this:
cmake_minimum_required(VERSION 3.12)
# set the project name and version
project(1D_DFT VERSION 0.1)
#Slate directories
set(slate_dir /opt/slate)
add_executable(1D_DFT test.cpp)
target_compile_definitions(1D_DFT PRIVATE SLATE_NO_CUDA)
target_compile_features (1D_DFT PRIVATE cxx_std_17)
target_compile_options (1D_DFT PRIVATE -fopenmp -Wall)
target_include_directories(1D_DFT PRIVATE ${slate_dir}/include)
target_link_directories (1D_DFT PRIVATE ${slate_dir}/lib)
target_link_libraries (1D_DFT PRIVATE slate blaspp lapackpp)
set_property(TARGET 1D_DFT PROPERTY BUILD_RPATH "${slate_dir}/lib")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | TallChuck |