Compiling and Debugging from the Command Line

Read this section only after installing GCC and gdb. For the specific method, see the article Compilers.

Compiling a cpp File with g++ from the Command Line

Manual Compilation

Enter g++ a.cpp at the command line to compile the file a.cpp (on Windows, the compiler's directory must be added to PATH in advance).

Some compilation options can be added during compilation:

  • -o <文件名>: Specify the filename of the executable output by the compiler.
  • -g: Add debugging information during compilation (required when debugging with gdb).
  • -Wall: Display all compilation warnings.
  • -O1, -O2, -O3, -Ofast: Optimize the compiled program. A later optimization level indicates that more optimization methods are used (enabling optimization affects debugging with gdb).
  • -DDEBUG: Define the DEBUG symbol during compilation (the symbol can be changed arbitrarily; for example, -DONLINE_JUDGE defines the ONLINE_JUDGE symbol).
  • -UDEBUG: Undefine the DEBUG symbol during compilation.
  • -lm, -lgmp: Link a library (here, math and gmp; the exact name to use must be found in the library documentation, but it is generally the same as the library name).
Note

On Unix, if the math library in the standard C library (math.h) is used, the -lm parameter must be added during compilation.1

How to Increase the Stack Size?

On Windows, the compilation option -Wl,--stack=536870912 can be used to increase the stack size to 512 MB. The number after the equals sign is the number of bytes.

On Unix, use ulimit -s [num] to adjust the stack size of the current terminal to [num] KiB.

Using GNU Make's Built-in Rules2

For C/C++ program source code named qwq.c/cpp, you can use make qwq to automatically compile it into a program named qwq.

To add additional compilation options, use export CFLAGS="xxx" (for C programs) or export CXXFLAGS="xxx" (for C++ programs). To add additional preprocessing options, use export CPPFLAGS="xxx". The above settings can also be written similarly to CFLAGS="xxx" CPPFLAGS="xxx" make qwq to specify the environment variables used during a single command execution.

Sanitizers

Introduction

Sanitizers are tools integrated into compilers for debugging C/C++ code. They check for errors that occur at runtime, such as out-of-bounds memory access and undefined behavior, by inserting checking code during compilation.

They are divided into the following types:

  • AddressSanitizer3: Detects out-of-bounds access to the heap, stack, and global variables, invalid memory deallocation, and memory leaks (experimental).
  • ThreadSanitizer4: Detects data races in multithreaded programs.
  • MemorySanitizer5: Detects reads from uninitialized memory.
  • UndefinedBehaviorSanitizer6: Detects undefined behavior.

Usage

The latest versions of clang++, g++, and MSVC (partially supported) have sanitizers built in, but their features and usage differ. Here, clang++ is used as an example:

$ clang++ -fsanitize=<name> test.cc

Here, <name> is the feature to enable (a sanitizer can be understood as a collection of features). For example:

$ clang++ -fsanitize=memory test.cc # Enable MemorySanitizer
$ clang++ -fsanitize=signed-integer-overflow test.cc # Enable signed-integer overflow detection

Then run the executable directly as usual. If the sanitizer detects an error, it outputs the error to the stderr stream, for example:

$ ./a.out
test.cc:3:5: runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'
Warning

g++ on Windows does not support sanitizers. You need to use a modified MinGW64 or another compiler.

As of version 17.14, MSVC has supported only AddressSanitizer since 16.0.

Time/Memory Cost

It is obvious that these debugging tools will significantly slow down the program and increase its memory usage. Their time/memory costs are as follows:

NameMemory multiplierTime multiplier
AddressSanitizerN/A2
ThreadSanitizer5~155~10
MemorySanitizerN/A3
UndefinedBehaviorSanitizerN/AN/A

Debugging with gdb from the Command Line

$ g++ a.cpp -o a -g
$ gdb ./a
GNU gdb (Ubuntu 12.1-0ubuntu1~22.04.2) 12.1
Copyright (C) 2022 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Type "show copying" and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<https://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
    <http://www.gnu.org/software/gdb/documentation/>.
--Type <RET> for more, q to quit, c to continue without paging--

Press c to continue. When it then displays Reading symbols from [filename]... and the text (gdb) appears, you can enter commands to debug.

The following are common commands organized by category:

Basic gdb Commands

CommandDescription
helpDisplay help information
quitExit gdb
file [filename]Load the program [filename] to debug

Execution Control Commands

CommandDescription
runRun the program until a breakpoint or the end of the program
continueContinue running until a breakpoint or the end of the program
nextExecute one step; enter a function when a function call is encountered
stepExecute one step; enter a function when a function call is encountered
finishRun until the current function returns, then stop and wait for a command
until [num]Run until the specified line [num], then stop and wait for a command
break [num]Set a breakpoint at line [num]; when the program runs to that line, stop and wait for a command
condition [id] [p]Set the condition for breakpoint [id]; the breakpoint is enabled only when expression [p] is satisfied
ignore [id] [num]Ignore the first [num] times the breakpoint is triggered
delete [id]Delete the breakpoint with the specified number
disable [id]Disable the breakpoint with the specified number
enable [id]Enable the breakpoint with the specified number
listList source code, continuing downward from the previous position, 10 lines at a time
list [num]List source code centered on line [num]
list [func-name]List source code with the specified function at the center
call [function]Call a function and print its return value

break [num] outputs the breakpoint number. You can also use break [func-name] to set a function breakpoint.

You can also use break [num] [p] when setting a breakpoint to achieve an effect similar to condition [id] [p].

Stack Frame Commands

CommandDescription
info argsView the function's arguments
backtraceView the calls and arguments of each function level
frameSelect a stack frame
upMove up one stack frame
downMove down one stack frame

Variable Commands

CommandDescription
print [p]Print the value of expression [p]; the expression can be used to modify a variable's value
display [p]Print the value of expression [p] each time execution pauses, without entering a function
watch [var]Watch the value of [var]; when the variable is written, it is automatically printed and execution pauses
rwatch [var]Watch the value of [var]; when the variable is read, it is automatically printed
awatch [var]When [var] is modified or written, it is automatically printed and execution pauses
set [assignment]Execute an assignment statement

The display and print commands both support controlling the output format. This is done by appending / and a format character after the command, such as print/display [var] (print the value of [var] in decimal). The supported format characters are:

Format characterCorresponding format
dDisplay the variable in decimal format
xDisplay the variable in hexadecimal format
aDisplay the variable in hexadecimal format
tDisplay the variable in binary format
cDisplay the variable in character format
fDisplay the variable in floating-point format
uDisplay the unsigned integer in decimal format
oDisplay the variable in octal format

Information Commands

CommandDescription
info breakpointsList all breakpoints
info localsList the local variables in the current stack frame
info argsList the function arguments in the current stack frame
info threadsList all threads
info programDisplay the current state of the program
info registersDisplay the current values of the registers
info frameDisplay information about the current stack frame

Other Commands

CommandDescription
enable pretty-printerEnable pretty-printer, which can print STL containers in a human-readable way
checkpoint7Create a checkpoint, allowing rollback to the checkpoint
restart [num]7Roll back to the [num]-th checkpoint
save breakpoints [filename]Save breakpoints to a file
source [filename]Import a breakpoint file
Tip

Most commands when debugging with gdb can be abbreviated to a unique sequence of letters. For example, breakpoint can be abbreviated as b, step as s, and info args as i ar. See the help command for details.

References and notes

Footnotes

  1. Catalogue of Built-In Rules ↩

  2. https://clang.llvm.org/docs/AddressSanitizer.html ↩

  3. https://clang.llvm.org/docs/ThreadSanitizer.html ↩

  4. https://clang.llvm.org/docs/MemorySanitizer.html ↩

  5. https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html ↩

  6. Instructions related to checkpoints are only applicable to the GNU/Linux platform. See the official GDB manual for details. ↩ ↩2

This content comes from OI Wiki: Compiling and Debugging from the Command Line. See the original for authors and revision history. AIOJ has adapted the formatting, in-site links, and resource paths.

Content is shared under CC BY-SA 4.0 and SATA license; additional terms are governed by the original notice. Thanks to the OI Wiki authors and contributors; per the SATA terms, please visit the OI Wiki repository and star it to show your support.