setting compiler/linker flags per target in CMake

Viewed 2073

I have created the following CMakelists.txt for my project which includes some files which need to be compiled with C and then will be linked with my C++ binary. I'm also using libasan.

cmake_minimum_required(VERSION 3.0)

SET(GCC_COVERAGE_COMPILE_FLAGS "-g3 -fsanitize=address -fno-omit-frame-pointer")
SET(GCC_COVERAGE_LINK_FLAGS    "-fsanitize=address -static-libasan")

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${GCC_COVERAGE_COMPILE_FLAGS}")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${GCC_COVERAGE_COMPILE_FLAGS}")

project(ABC_PROXY VERSION 1.0.0 LANGUAGES C CXX)

add_executable(abc_proxy
src/file1.c
src/main.cpp
)

target_include_directories(abc_proxy PRIVATE /home/vishal/cpp_file/new /home/vishal/cpp_file/new/framework)
SET(CMAKE_EXE_LINKER_FLAGS  "${CMAKE_EXE_LINKER_FLAGS} ${GCC_COVERAGE_LINK_FLAGS}")

In the above file I only have one target binary. But now I want to have 2 binaries. One will be compiled with libasan and the other will be compiled without it. How can I use different flag values in the 'CMAKE_EXE_LINKER_FLAGS ' , 'CMAKE_CXX_FLAGS' and 'CMAKE_CXX_FLAGS' for each binary target?

1 Answers

Ok, so after browsing through different answers here I've made the CMakelists.txt given below and it works in this case.

cmake_minimum_required(VERSION 3.0)

project(ABC_PROXY VERSION 1.0.0 LANGUAGES C CXX)

add_executable(abc_proxy_with_asan
src/file1.c
src/main.cpp
)

set_target_properties(abc_proxy_with_asan PROPERTIES COMPILE_FLAGS "-g3 -fsanitize=address -fno-omit-frame-pointer")
set_target_properties(abc_proxy_with_asan PROPERTIES LINK_FLAGS "-fsanitize=address -static-libasan")
target_include_directories(abc_proxy_with_asan PRIVATE /home/vishal/cpp_file/new /home/vishal/cpp_file/new/framework)

add_executable(abc_proxy
src/file1.c
src/main.cpp
)

set_target_properties(abc_proxy PROPERTIES COMPILE_FLAGS "-g3 -fno-omit-frame-pointer")
target_include_directories(abc_proxy PRIVATE /home/vishal/cpp_file/new /home/vishal/cpp_file/new/framework)
Related