Search code examples
c++cmake

CMake - How to check for a compiler AND linker flag at the same time


In my CMakeLists.txt I want to enable AddressSanitizer if it will compile and link (because I want the static version which might not be installed). Enabling it would be:

string(APPEND CMAKE_CXX_FLAGS " -fno-omit-frame-pointer -fsanitize=address -static-libasan")
string(APPEND CMAKE_LINKER_FLAGS " -fno-omit-frame-pointer -fsanitize=address -static-libasan")

So I tried to use check_cxx_compiler_flag like this:

check_cxx_compiler_flag("-fno-omit-frame-pointer -fsanitize=address -static-libasan" sanitize_compile)
check_linker_flags(CXX "-fno-omit-frame-pointer -fsanitize=address -static-libasan" sanitize_link)

But that will test the flags separately - which won't work. Is there any functionality like check_cxx_compiler_and_linker_flags in CMake without writing it myself?


Solution

  • try_compile can accomplish this.

    Create a small CMakeLists.txt project that adds compiler/linker flags:

    cmake_minimum_required(3.16)
    project(STATIC_ASAN LANGUAGES C)
    
    # Source for minimal executable
    file(WRITE main.c [==[
    int main(int argc, char *argv[]) {
      (void)argc; (void)argv;
      return 0;
    }
    ]==])
    
    add_executable(foo main.c)
    
    target_compile_options(foo PRIVATE -fsanitize=address -static-libasan)
    target_compile_options(foo PRIVATE -fsanitize=address -static-libasan)
    

    Put this CMakeLists.txt in a directory EX: asan/CMakeLists.txt

    Now you can use try_compile in your main CMakeLists.txt

    try_compile(STATIC_ASAN_SUPPORTED PROJECT asan
        SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/asan
    )
    
    if (STATIC_ASAN_SUPPORTED)
        message(STATUS "Static asan supported")
    endif()