Change debug flag from -g to -ggdb3 using CMake

Viewed 664

Consider the following simple C++ program:

// main.cpp
#include <iostream>

int main()
{
    std::cout << "Hello World" << std::endl;
    return 0;
}

I am using CMake to generate my Makefile for this project, which I then build using GNU Make and g++. My CMakeLists.txt file looks like this (it is actually more complex, this is of course simplified):

cmake_minimum_required(VERSION 3.20)
project(HelloWorld VERSION 1.0 LANGUAGES CXX)

add_executable(HelloWorld main.cpp)

Everything works, but when building a debug build:

cmake -DCMAKE_BUILD_TYPE=Debug ..

I noticed the debugger flag that is used is -g. When running make VERBOSE=1 to see what flags are used, here what shows up when compiling main.cpp:

[ 50%] Building CXX object CMakeFiles/HelloWorld.dir/main.cpp.o
/usr/bin/c++ -g -MD -MT CMakeFiles/HelloWorld.dir/main.cpp.o -MF CMakeFiles/HelloWorld.dir/main.cpp.o.d -o CMakeFiles/HelloWorld.dir/main.cpp.o -c /home/HelloWorld/main.cpp

Notice the -g flag which is put there automatically by CMake to add debugging information.

How can I change it to -ggdb3 instead?

1 Answers

The -g flags is automatically set in builtin cached variable CMAKE_C_FLAGS_DEBUG CMAKE_CXX_FLAGS_DEBUG CMAKE_C_FLAGS_RELWITHDEBINFO and CMAKE_CXX_FLAGS_RELWITHDEBINFO, which contains default compile options for corresponding build types. You may replace and force-set these cached variables as you like.

string(REGEX REPLACE "\\b-g\\b" "-ggdb3" tmp_value "${CMAKE_C_FLAGS_DEBUG}")
set_property(CACHE CMAKE_C_FLAGS_DEBUG PROPERTY VALUE "${tmp_value}")

And at last, you may actually don't need to use -ggdb3 at all.

Related