CMake环境下段错误定位咨询:如何找到触发段错误的代码行
Hey there! Let's work through your segmentation fault debugging problem and fix that make error along the way.
/usr/bin/make: invalid option -... Error That error pops up when you're passing an invalid flag directly to make (like accidentally running make -g). CMake handles debug flags behind the scenes, so you don't need to pass -g to make itself. Instead, we'll configure CMake to generate a debug build first, then run make normally.
CMake uses the CMAKE_BUILD_TYPE variable to toggle between debug and release builds. To generate a build with full debug symbols (including the -g flag you're missing), do one of these:
If you're starting fresh:
# Create a build directory (always use out-of-source builds with CMake!) cmake -S . -B build -DCMAKE_BUILD_TYPE=DebugThis tells CMake to generate makefiles that add
-gand-O0(no optimization, critical for accurate debugging) to every compile command.If you already have a build directory:
cd build cmake -DCMAKE_BUILD_TYPE=Debug ..
Then recompile your project with:
make -C build # Or just cd into build and run make
Once you have a debug build, you can use a debugger to pinpoint exactly which line is causing the crash. The most common tools are gdb (GNU Debugger) and lldb (LLVM Debugger):
Using GDB
- Launch your executable in GDB:
gdb ./build/your_executable_name - Start the program with
run:(gdb) run - When the segmentation fault happens, GDB will pause and show you the exact code line where the crash occurred. To see the full call stack (to understand how you got to that line), run:
(gdb) bt
Using LLDB
If you're working with LLVM/clang, lldb works similarly:
- Launch the executable:
lldb ./build/your_executable_name - Start the program:
(lldb) run - After the crash, get the call stack with:
(lldb) bt
If you need more control over debug flags or want to verify everything is set up correctly:
- Add more detailed debug info: Use
-g3instead of the default-gto include macro definitions and extra debug data. Set this with:
(Swapcmake -S . -B build -DCMAKE_BUILD_TYPE=Debug -DCMAKE_CXX_FLAGS_DEBUG="-g3 -O0"CMAKE_CXX_FLAGS_DEBUGwithCMAKE_C_FLAGS_DEBUGif you're writing C code.) - See full compile commands: Enable verbose make output to confirm
-gis being added:
When you runcmake -S . -B build -DCMAKE_BUILD_TYPE=Debug -DCMAKE_VERBOSE_MAKEFILE=ONmake, you'll see every compile command, so you can check for the-gflag yourself.
内容的提问来源于stack exchange,提问作者Christoph

