Chapter 31: Debugger

Introduction

Debugging is the process of identifying and fixing errors in your code. These errors can be broadly categorized into syntax errors and semantic (logic) errors.

Debugging Techniques

Using std::cerr for Debugging

std::cerr provides unbuffered output, making it suitable for debugging purposes as the output is displayed immediately.

Example

#define ENABLE_DEBUG // comment out to disable debugging

#ifdef ENABLE_DEBUG
std::cerr << "getUserInput() called\n";
#endif

int getUserInput()
{
    return 5;
}

int main()
{
    #ifdef ENABLE_DEBUG
    std::cerr << "main() started\n";
    #endif

    int value = getUserInput();

    #ifdef ENABLE_DEBUG
    std::cerr << "User input: " << value << '\n';
    #endif

    return 0;
}

Using Loggers

Loggers can be used to provide more sophisticated logging capabilities. std::clog can be redirected to a file, or third-party logging libraries such as spdlog can be used.

Example Using std::clog

#include <iostream>
#include <fstream>

int main()
{
    std::ofstream logFile("log.txt");
    std::clog.rdbuf(logFile.rdbuf()); // Redirect std::clog to logFile

    std::clog << "Program started\n";

    int value = 42;
    std::clog << "Value: " << value << '\n';

    std::clog << "Program ended\n";
    return 0;
}

Example Using spdlog

#include <spdlog/spdlog.h>
#include <spdlog/sinks/basic_file_sink.h>

int main()
{
    auto logger = spdlog::basic_logger_mt("basic_logger", "logs/basic.txt");

    logger->info("Program started");

    int value = 42;
    logger->info("Value: {}", value);

    logger->info("Program ended");
    return 0;
}

Conclusion

Using std::cerr, std::clog, or third-party logging libraries can significantly enhance your debugging capabilities, making it easier to identify and fix errors in your code. Proper logging can provide valuable insights into the execution flow and state of your program.