LLVM address sanitizer with CMake

I am trying to compile the simplest executable using clang with -fsanitize=address option. It’s very simple to do that using clang directly. But my point is to do it through CMake.

There is how I am doing it. CMakeLists.txt file:

cmake_minimum_required(VERSION 3.5.1 FATAL_ERROR)
project(TestSanitizer VERSION 0.1.0 LANGUAGES CXX)
add_executable(Test main.cpp)
target_compile_options(Test PUBLIC
    -std=c++17
    -Werror
    -Weverything
    -Wno-c++98-compat
    -Wno-c++98-c++11-c++14-compat
    -Wno-c++98-compat-pedantic
    -fsanitize=address)

main.cpp:

int main(int, const char**) { return 0; }

configure and make using bash script (config_gen_build.sh):

if [ -d "bin" ]; then
    rm -rf bin
fi

mkdir bin
cd bin

#config and gen
export CC=/usr/bin/clang-5.0
export CXX=/usr/bin/clang++-5.0
cmake ./../

#build
make

Finally, the error I am getting: enter image description here

What’s wrong here? Should I link with some library?

Answer

The easiest way to link with the address sanitizer is to specify -fsanitize=address as a linker, as well as a compiler, option. This causes clang or gcc to pass the correct libraries and flags to the linker.