'How to run sanitizers on whole project

I'm trying to get familiar with sanitizers as ASAN, LSAN etc and got a lot of useful information already from here: https://developers.redhat.com/blog/2021/05/05/memory-error-checking-in-c-and-c-comparing-sanitizers-and-valgrind

I am able to run all sort of sanitizers on specific files, as shown on the site, like this:

clang -g -fsanitize=address -fno-omit-frame-pointer -g ../TestFiles/ASAN_TestFile.c
ASAN_SYMBOLIZER_PATH=/usr/local/bin/llvm-symbolizer ./a.out >../Logs/ASAN_C.log 2>&1

which generates a log with found issue. Now I would like to extend this to run upon building the project with cmake. This is the command to build it at the moment:

cmake -S . -B build
cd build
make

Is there any way I can use this script with adding the sanitizers, without having to alter the cmakelist.txt file??

For instance something like this:

cmake -S . -B build
cd build
make -fsanitize=address
./a.out >../Logs/ASAN_C.log 2>&1

The reason is that I want to be able to build the project multiple times with different sanitizers (since they cannot be used together) and have a log created without altering the cmakelist.txt file (just want to be able to quickly test the whole project for memory issues instead of doing it for each file created).



Solution 1:[1]

You can add additional compiler flags from command line during the build configuration:

cmake -D CMAKE_CXX_FLAGS="-fsanitize=address" -D CMAKE_C_FLAGS="-fsanitize=address"  /path/to/CMakeLists.txt

If your CMakeLists.txt is configured properly above should work. If that does not work then try adding flags as environment variable:

cmake -E env CXXFLAGS="-fsanitize=address" CFLAGS="-fsanitize=address" cmake /path/to/CMakeLists.txt

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 A. K.