3

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?

Employed Russian
  • 199,314
  • 34
  • 295
  • 362
BobMorane
  • 3,870
  • 3
  • 20
  • 42
  • 1
    Related Q/A, but I would imagine that there are better ways to do this nowadays: https://stackoverflow.com/questions/10085945/set-cflags-and-cxxflags-options-using-cmake –  Jul 20 '21 at 20:20
  • Note that `-g` and `-ggdb3` are mostly equivalent, except the latter records macro definitions (in a horribly inefficient way). Why do you _want_ `-ggdb3` ? – Employed Russian Jul 20 '21 at 22:26
  • I am porting plain Makefiles to CMake. Those Makefiles had that `-ggdb3` flag, that's mostly why. If it becomes to hard to do in CMake, I might end up using the `-g` flag instead. – BobMorane Jul 20 '21 at 23:21

1 Answers1

0

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.

jiandingzhe
  • 1,881
  • 15
  • 35
  • It does not seem to work: I set those two lines (replacing `CMAKE_C_FLAGS_DEBUG` by `CMAKE_CXX_FLAGS_DEBUG`) just before my `add_executable` call, but the `-g` switch is still there, and `-ggdb3` is not. Maybe I'm doing something wrong? – BobMorane Jul 21 '21 at 10:32
  • Late to the party, but `\b` matches word boundaries; I believe the string should be `"-g\\b"` instead of `"\\b-g\\b"` (as there is no word boundary left of the hyphen). – OnlineCop Apr 12 '23 at 16:47