Ubuntu下VsCode和CMake联合调试C++工程

一、本机环境配置

1.1 安装C++编译功能包

$ sudo apt install build-essential

1.2 安装CMake

参考如下:安装指定版本CMake

1.3 安装Vscode

安装Vscode并配置好C++开发需要的插件

二、CMakeLists.txt配置

根据不同工程编写不同的CMakeLists.txt,但是需要确保CMakeLists.txt有如下命令:

# 设置编译模式
set( CMAKE_BUILD_TYPE "Debug" )
set(CMAKE_CXX_FLAGS_DEBUG "$ENV{CXXFLAGS} -O0 -Wall -g2 -ggdb")
set(CMAKE_CXX_FLAGS_RELEASE "$ENV{CXXFLAGS} -O3 -Wall")
add_definitions(-std=c++11)

其中add_definitions(-std=c++11)可以用来指定C++版本

CMakeLists.txt样例:

cmake_minimum_required(VERSION 3.5)

project(hello_library)

############################################################
# Create a library
############################################################

#Generate the static library from the library sources
add_library(hello_library STATIC 
    src/Hello.cpp
)

# 设置编译模式
set( CMAKE_BUILD_TYPE "Debug" )
set(CMAKE_CXX_FLAGS_DEBUG "$ENV{CXXFLAGS} -O0 -Wall -g2 -ggdb")
set(CMAKE_CXX_FLAGS_RELEASE "$ENV{CXXFLAGS} -O3 -Wall")
add_definitions(-std=c++11)

target_include_directories(hello_library
    PUBLIC 
        ${PROJECT_SOURCE_DIR}/include
)


############################################################
# Create an executable
############################################################

# Add an executable with the above sources
add_executable(hello_binary 
    src/main.cpp
)

# link the new hello_library target with the hello_binary target
target_link_libraries( hello_binary
    PRIVATE 
        hello_library
)

三、编译工程

主要命令如下:

mkdir build
cd build
cmake ..
make

四、调试程序

主要步骤如下

  • 在需要调试的程序中打断点
  • 按Ctrl + F5开始调试程序
  • 按F5步进调试

猜你喜欢

转载自blog.csdn.net/LiuXF93/article/details/123066248