Konstantin Lazukin
Konstantin Lazukin

Reputation: 246

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?

Upvotes: 5

Views: 4282

Answers (2)

b_squared
b_squared

Reputation: 81

I believe you forgot to pass -fsanitize to the link options as the other answer mentioned. So you need both:

target_compile_options(Foo PUBLIC -fsanitize=address)
target_link_options(Foo PUBLIC -fsanitize=address)

Alternatively, to enable this for you entire project, you can use the following CMake directives at the beginning of your project file:

add_compile_options(-fsanitize=address)
add_link_options(-fsanitize=address)

Upvotes: 5

n. m. could be an AI
n. m. could be an AI

Reputation: 119847

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.

Upvotes: 7

Related Questions