CMake Tutorial: Supporting GDB Debugging

Table of Contents

    • 1. Introduction

    • 2. How to Support GDB Debugging

    • 3. Code Examples

      • [1] Write demo.c

      • [2] Write CMakeLists.txt

      • [3] Compile

      • [4] GDB Debugging

1. Introduction

The combination of CMake and GDB indeed makes the development work of C or C++ easier, enabling cross-platform project builds and source-level debugging.
This article details how to configure a project using CMake for debugging with GDB, along with a C language demo.

2. How to Support GDB Debugging

Enabling GDB support in CMake is straightforward; you just need to specify the Debug mode with the -g option:
set(CMAKE_BUILD_TYPE "Debug")
set(CMAKE_CXX_FLAGS_DEBUG "$ENV{CXXFLAGS} -O0 -Wall -g -ggdb")
set(CMAKE_CXX_FLAGS_RELEASE "$ENV{CXXFLAGS} -O3 -Wall")
1. Add these three lines to CMakeLists.txt.
In CMake, there is a variable CMAKE_BUILD_TYPE, which can take values like Debug, Release, RelWithDebInfo, and MinSizeRel.
When this variable is Debug, CMake will use the strings in the variables CMAKE_CXX_FLAGS_DEBUG and CMAKE_C_FLAGS_DEBUG as compilation options to generate the Makefile.
2. The -g option during compilation generates an executable file with debugging information.
This debugging information includes variable names, function names, file names, etc., allowing the debugger (like GDB) to easily track the execution process and view variable values, function call stacks, and more.
Using the -g option during compilation makes it easier to locate issues in the program while debugging, enhancing debugging efficiency.

3. Code Examples

Project Structure
project/
│
├── CMakeLists.txt
└── demo.c

[1] Write demo.c

#include <stdio.h>

void print_val(int val) {
    printf("value: %d\n", val);
}

int main() {
    int a = 10;
    int b = 20;
    print_val(a);
    print_val(b);
    return 0;
}

[2] Write CMakeLists.txt

cmake_minimum_required (VERSION 3.10)
  
# Project Name
project (demo)

set(CMAKE_BUILD_TYPE "Debug")
set(CMAKE_CXX_FLAGS_DEBUG "$ENV{CXXFLAGS} -O0 -Wall -g -ggdb")
set(CMAKE_CXX_FLAGS_RELEASE "$ENV{CXXFLAGS} -O3 -Wall")

# Add executable
add_executable(demo demo.c)                          

[3] Compile

Execute the following commands in the project directory
mkdir build
cd build;cmake ..
make

[4] GDB Debugging

CMake Tutorial: Supporting GDB Debugging

Leave a Comment