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 theDEBUGsymbol during compilation (the symbol can be changed arbitrarily; for example,-DONLINE_JUDGEdefines theONLINE_JUDGEsymbol).-UDEBUG: Undefine theDEBUGsymbol 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:
| Name | Memory multiplier | Time multiplier |
|---|---|---|
| AddressSanitizer | N/A | 2 |
| ThreadSanitizer | 5~15 | 5~10 |
| MemorySanitizer | N/A | 3 |
| UndefinedBehaviorSanitizer | N/A | N/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
| Command | Description |
|---|---|
help | Display help information |
quit | Exit gdb |
file [filename] | Load the program [filename] to debug |
Execution Control Commands
| Command | Description |
|---|---|
run | Run the program until a breakpoint or the end of the program |
continue | Continue running until a breakpoint or the end of the program |
next | Execute one step; enter a function when a function call is encountered |
step | Execute one step; enter a function when a function call is encountered |
finish | Run 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 |
list | List 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
| Command | Description |
|---|---|
info args | View the function's arguments |
backtrace | View the calls and arguments of each function level |
frame | Select a stack frame |
up | Move up one stack frame |
down | Move down one stack frame |
Variable Commands
| Command | Description |
|---|---|
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 character | Corresponding format |
|---|---|
d | Display the variable in decimal format |
x | Display the variable in hexadecimal format |
a | Display the variable in hexadecimal format |
t | Display the variable in binary format |
c | Display the variable in character format |
f | Display the variable in floating-point format |
u | Display the unsigned integer in decimal format |
o | Display the variable in octal format |
Information Commands
| Command | Description |
|---|---|
info breakpoints | List all breakpoints |
info locals | List the local variables in the current stack frame |
info args | List the function arguments in the current stack frame |
info threads | List all threads |
info program | Display the current state of the program |
info registers | Display the current values of the registers |
info frame | Display information about the current stack frame |
Other Commands
| Command | Description |
|---|---|
enable pretty-printer | Enable pretty-printer, which can print STL containers in a human-readable way |
checkpoint7 | Create a checkpoint, allowing rollback to the checkpoint |
restart [num]7 | Roll 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
-
https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html ↩
-
Instructions related to checkpoints are only applicable to the GNU/Linux platform. See the official GDB manual for details. ↩ ↩2