在ubuntu下调试C++ 本人觉得VSCode比较好用。

步骤如下:

1. 编写.cpp,.h文件

自行完成自己的程序。

2. 编写CMakeLists.txt。下面是一个比较好用的模板。

根目录为:

PROJECT(mmseg CXX) #项目名称

#Cmake最低版本要求
CMAKE_MINIMUM_REQUIRED(VERSION 2.6) #允许gdb调试
set(CMAKE_BUILD_TYPE "Debug")
set(CMAKE_CXX_FLAGS_DEBUG "$ENV{CXXFLAGS} -O0 -Wall -g -ggdb")
set(CMAKE_CXX_FLAGS_RELEASE "$ENV{CXXFLAGS} -O3 -Wall") #添加C++11支持及其他选项
set(CMAKE_CXX_FLAGS "-std=c++0x ${CMAKE_CXX_FLAGS} -g -ftest-coverage -fprofile-arcs -Wno-deprecated")
#set(CMAKE_CXX_FLAGS "-std=c++0x ${CMAKE_CXX_FLAGS -g -ftest-coverage -fprofile-arcs"}) #添加dict子目录
add_subdirectory(dict) #当前目录下所有源文件赋给DIR_SRCS
AUX_SOURCE_DIRECTORY(. DIR_SRCS) #生成可执行文件
add_executable(mmseg ${DIR_SRCS}) #添加C++11编译选项,但是只有CMAKE 3.1支持
#target_compile_features(mmseg PRIVATE cxx_range_for) #添加链接库
target_link_libraries(mmseg Dict)

子目录为:

#查找当前目录下所有源文件
#并将结果保存在DIR_LIB_SRCS变量中
aux_source_directory(. DIR_LIB_SRCS) #生成链接库
add_library(Dict ${DIR_LIB_SRCS})

3. 编写一个compile.sh

mkdir -p build
rm -rf build/*
cd build
cmake .. -DCMAKE_VERBOSE_MAKEFILE=ON -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -DCMAKE_BUILD_TYPE=Debug
make

4. build and run tasks

使用Ctrl+Shift+P快捷键,并且在下拉菜单中选择>tasks: configure task,然后在下拉菜单中选择ohter 用于build程序。在生成的tasks.json中加入build与debug内容

{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "CMake build",
"type": "shell",
"command": "./compile.sh",
"group": {
"kind": "build",
"isDefault": true
},
"problemMatcher": [
"$gcc"
]
},
{
"label": "run",
"type": "shell",
"command": "./build/your_run_file", #!! change here for your config
"group": {
"kind": "build",
"isDefault": true
},
"problemMatcher": [
"$gcc"
]
}
]
}

  

然后使用Ctrl+Shift+P快捷键,并且在下拉菜单中选择>Tasks: Run Task,选择build或者run tasks就可以build并生成可执行文件。

这时可能会提示:

/bin/bash: ./compile.sh: Permission denied
The terminal process terminated with exit code: 126

错误,使用命令

sudo chmod 755 compile.sh

5.debug程序

由于使用cmake来build程序,已经在compile.sh中加入了debug信息-DCMAKE_BUILD_TYPE=Debug

点击VSCode左侧的小虫子按钮,添加一个新的configuration,选择C++(GDB/LLDB)。这时产生一个launch.json文件,添加

{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "(gdb) Launch",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/build/blob_demo", #!! change here for your config
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
}
]
}

在你的.cpp文件中设置一个断点,点击运行按钮,就可以debug了。

05-11 20:01