Skip to content

Wiki

Linux开发环境搭建与测试

About 20 min read

Existing English translations were reused. 11 current source blocks remain in Simplified Chinese, without triggering paid translation.

本节接着 C++开发环境搭建与测试 往下做,适用于 Ubuntu / Debian 和 Fedora。 Windows 用户请看 Windows开发环境搭建与测试。

In this chapter, we won't change the code first; we'll do just one very specific thing:

Run my prepared CMake template on Linux.

If you are just starting to learn C++, seeing names like CMake、Ninja、target_link_libraries need not make you nervous. This chapter does not require you to understand all their principles; for now, just follow the steps to get the project running. When you later learn about header files, writing code across multiple files, and third-party libraries, coming back to this content will feel more natural.

The complete CMake template details are placed in the later CMake project template section. This chapter focuses on only two things:

  1. Can your computer compile and run the C++ project?
  2. Can VSCode use F5 to debug this project?

1.Final effect of this chapter

After completing this chapter, you will get a folder named hello_cpp containing a complete CMake template project.

When running the template as-is, the output is similar to:

[lib1] Vector v = 1 2 3
[lib1] Norm = 3.74166
[lib2] Matrix m =
1 2
3 4
[lib2] Determinant = -2

This chapter will proceed in the following order:

  1. Install the C++ development tools on Ubuntu or Fedora.
  2. Download the CMake template I have prepared.
  3. First run the template as-is to confirm there are no issues with the environment.
  4. Take a look at which files in the template are relevant to the later learning.
  5. Use VSCode and press F5 to debug the template program.

First, let's get familiar with a few names so they won't seem too abrupt when you see them later:

Name Understand it this way for now
g++ The compiler that actually compiles C++ code
CMake Read CMakeLists.txt, generate build rules
Ninja Perform compilation according to the rules generated by CMake
GDB Debugger, used when pressing F5 in VSCode
lib1 / lib2 The two example small libraries included in the template; this chapter will not modify them for now
cmake_template The executable program name currently generated by the template

Note:hello_cpp is the name of the folder we cloned, andcmake_template is the name of the program currently generated by this project. They are not the same thing.

2.Install basic tools

2.1.Ubuntu / Debian

sudo apt update
sudo apt install git cmake ninja-build gcc g++ gdb libeigen3-dev

This is installed here libeigen3-devbecause the original template example uses Eigen. Install it first, and the template will run directly.

2.2.Fedora

sudo dnf install git cmake ninja-build gcc gcc-c++ gdb eigen3-devel
Ubuntu/Debian Fedora/RHEL Description
git git Version control tool
cmake cmake CMake build tool
ninja-build ninja-build Ninja build tool
gcc gcc C compiler
g++ gcc-c++ C++ compiler
gdb gdb GNU debugger
libeigen3-dev eigen3-devel Eigen3 C++ numerical library development files

3.Check whether the tool is installed successfully.

git --version
cmake --version
ninja --version
g++ --version
gdb --version

The fact that these commands can all output version numbers indicates that the basic environment is already usable.

4.Install VScode

https://code.visualstudio.com/Download

If it is a Debian-based system, download the deb; if it is an RHEL-based system, download the rpm.

After downloading, click the browser, find the folder containing this installation package, and open a terminal at that path.

Debian-based: entersudo apt install ./codeThen press thetabkey to complete the filename, and press Enter.

RHEL-based: entersudo dnf install ./codethen presstabkey to complete the filename, and press Enter.

For example, after completion:

sudo dnf install ./code-1.102.1-1752598767.el8.x86_64.rpm

5.Configure VSCode

Then open VSCode and enter the following command in the terminal.

code

Then you can configure an environment to be used exclusively for the C++ environment, avoiding conflicts with the default environment.

alt text

Just make some settings, follow my lead.

alt text

Select the CMake configuration you created

alt text

6.Install the VSCode extension

It is recommended to install these extensions in VSCode:

  1. CMake Tools
  2. C/C++
  3. C/C++ DevTools
  4. clangd

Their division of labor is:

扩展 作用
CMake Tools 识别 CMakePresets.json,执行 configure/build,选择 target,管理 CMake 工程构建流程
C/C++ 微软官方 C/C++ 扩展,提供基础 IntelliSense、断点调试、GDB/LLDB 调试配置支持
C/C++ DevTools C/C++ 扩展的辅助工具,提供更方便的调试信息展示、内存/寄存器/变量查看等增强能力
clangd 基于 compile_commands.json 提供更准确的代码补全、跳转定义、查找引用、诊断提示、重构能力

Simply put:

  • CMake Tools Responsible for build engineering;
  • C/C++ and C/C++ DevTools mainly responsible for debugging;
  • clangd mainly responsible for code hints, navigation, diagnostics, and refactoring.

If you use clangd for code suggestions, it is recommended to disable or weaken the IntelliSense of the C/C++ extension to avoid duplicate or conflicting suggestions caused by two language servers working at the same time.

alt text

7.Clone CMake template

git clone https://github.com/tungchiahui/CMake_Template.git hello_cpp
cd hello_cpp
code .

Here, the project directory is named hello_cpp. All subsequent commands are assumed to be executed in this directory.

When you first start learning, do not worry about Git history, and do not rush to change many files. The first step is to do only one thing: confirm that this template can run on your computer.

Select the CMake configuration you created

alt text

8.First run the template as-is

8.1.Run it via the command line

Don't rush to change the code yet. Followctrl + ~Open the VS Code terminal and run the following three commands:

cmake --preset linux-debug
cmake --build --preset linux-debug
./build/linux-debug/src/cmake_template

If the output is similar to:

[lib1] Vector v = 1 2 3
[lib1] Norm = 3.74166
[lib2] Matrix m =
1 2
3 4
[lib2] Determinant = -2

alt text

This indicates that the project, compiler, CMake, Ninja, and Eigen are all working properly. At this point, the most troublesome environment setup is already done.

Note: During daily development, you can run the program in the build directory directly, without needing to install every time.

Only when verifying the installation layout is it needed:

cmake --install build/linux-debug
./install/linux-debug/bin/cmake_template

The following indicates success!

[lib1] Vector v = 1 2 3
[lib1] Norm = 3.74166
[lib2] Matrix m =
1 2
3 4
[lib2] Determinant = -2

alt text

8.2.Run in VSCode graphical mode

We need to use the VSCode graphical method to run the above commands:

点击左侧边的CMake:

  1. 首先要配置cmake --preset linux-debug,等同于在界面中是点击Configure按钮,并选择Linux Debug:

    alt text

  2. 然后cmake --build --preset linux-debug这个配置会在你配置configure时被自动配置:

    alt text

    然后你要手动点击左下角的Build按钮来进行build:

    alt text

  3. 然后./build/linux-debug/src/cmake_template运行这个程序等同于:

    先配置程序路径: alt text

    运行程序: Debug是对程序进行debug,而Launch是直接运行程序不debug,除非你有debug需求,一般咱们直接用launch. alt text

    alt text

    除了上面的操作入口,VSCode 底部状态栏中,Build 按钮旁边也有 Debug 和 Launch 快捷按钮。选择好 cmake_template target 并完成构建后,可以直接点击这里运行或调试程序。

    alt text

Next, we will explain how to put the generated artifacts intoinstall, generally, you only need to install if you are going to release a program, etc.; normally, just use the above build. (After testing, change back to the build configuration.)

  1. cmake --install build/linux-debugEquivalent to: In VSCode press Ctrl+Shift+P, then enter CMake: Install.

    alt text

    Explanation: This command will invoke the currently configured build preset corresponding to cmake --install <buildDir>. If you selected the linux-debug preset, it is equivalent to cmake --install build/linux-debug.

  2. Then./install/linux-debug/bin/cmake_templateRunning this program is equivalent to: First configure the program path:

    alt text

    The way to run the program is the same as above, also click DebugorLaunch.

9.Template current structure

Now let's look at the files in the template related to this chapter. For now, you don't need to understand every CMake option; just know that src/ code goes below:

.
├── CMakeLists.txt
├── CMakePresets.json
├── cmake/
│   ├── ProjectOptions.cmake
│   └── WindowsRuntime.cmake
└── src/
    ├── CMakeLists.txt
    ├── main.cpp
    ├── lib1/
    │   ├── CMakeLists.txt
    │   ├── inc/lib1/eigen3_test.hpp
    │   └── src/eigen3_test.cpp
    └── lib2/
        ├── CMakeLists.txt
        ├── inc/lib2/eigen3_test.hpp
        └── src/eigen3_test.cpp

The most important thing here is:

Location Purpose
src/main.cpp Program entry point; runtime starts here
src/lib1/ First example mini-library
src/lib2/ Second example mini-library
CMakeLists.txt Tells CMake how to build this project

In this chapter, you only need to recognize these positions; you do not need to modify them.

10.Frequently Asked Questions

10.1.Ninja not found

Error similar to:

CMake was unable to find a build program corresponding to "Ninja"

Install:

sudo apt install ninja-build

Or:

sudo dnf install ninja-build

10.2.gdb not found

If GDB cannot be found during debugging:

sudo apt install gdb

Or:

sudo dnf install gdb

10.3.Build exception after changing CMakeLists.txt

本章没有要求修改 CMakeLists.txt。如果你后面章节改了 CMake 文件,可以先重新 configure:

cmake --preset linux-debug

Or delete the build directory:

rm -rf build/linux-debug
cmake --preset linux-debug

10.4.clangd 找不到标准库头文件

先确认已经安装 clangd 程序,安装扩展和安装程序是两件事。Ubuntu / Debian 可以安装 clangd,Fedora 可以安装 clang-tools-extra。模板根目录的 .clangd 保持:

CompileFlags:
  CompilationDatabase: build/linux-debug

执行 Configure 后,再用命令面板中的 clangd: Restart language server 重新加载。

10.5.按 F5 没有进入 CMake 调试

先选择 cmake_template target,直接使用 CMake Tools 的 Debug 按钮。如果想把 F5 固定为同一个操作,打开 VSCode 的键盘快捷方式,搜索 CMake: Debug,把它绑定到 F5。这样不需要手写 launch.json,也不会误用“只编译当前文件”的调试方式。

11.What to learn next

This chapter is only meant to first give you a small project that can run and be debugged.

Subsequent chapters will start with the C++ basic syntax:

  1. C++ Basic Introduction
  2. Data Types and Data Storage
  3. Input and Output
  4. Operators
  5. Program Flow Structure

In the next chapter, we will first only modify src/main.cpp. When you learn about splitting functions across files, then organize lib1 / lib2; when you learn about project organization, third-party libraries, and build systems, come back and look at CMake project template.