You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CMake环境下段错误定位咨询:如何找到触发段错误的代码行

Hey there! Let's work through your segmentation fault debugging problem and fix that make error along the way.

Fixing the /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.

Enabling Debug Symbols in CMake

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=Debug
    

    This tells CMake to generate makefiles that add -g and -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
Finding the Segmentation Fault Line with a Debugger

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

  1. Launch your executable in GDB:
    gdb ./build/your_executable_name
    
  2. Start the program with run:
    (gdb) run
    
  3. 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:

  1. Launch the executable:
    lldb ./build/your_executable_name
    
  2. Start the program:
    (lldb) run
    
  3. After the crash, get the call stack with:
    (lldb) bt
    
Extra CMake Debugging Options

If you need more control over debug flags or want to verify everything is set up correctly:

  • Add more detailed debug info: Use -g3 instead of the default -g to include macro definitions and extra debug data. Set this with:
    cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug -DCMAKE_CXX_FLAGS_DEBUG="-g3 -O0"
    
    (Swap CMAKE_CXX_FLAGS_DEBUG with CMAKE_C_FLAGS_DEBUG if you're writing C code.)
  • See full compile commands: Enable verbose make output to confirm -g is being added:
    cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug -DCMAKE_VERBOSE_MAKEFILE=ON
    
    When you run make, you'll see every compile command, so you can check for the -g flag yourself.

内容的提问来源于stack exchange,提问作者Christoph

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:44:18