第 1 節

C++ Development Environment Setup and Testing

0瀏覽次數0訪問次數--跳出率--平均停留

This chapter won't involve modifying code, just focusing on one very specific task.

Run my prepared CMake template on Linux.

If you're just starting to learn C++, don't be intimidated by names like CMake, Ninja, target_link_libraries. This chapter doesn't require you to fully understand their underlying principles—just follow the steps to get the project running. Later, when you learn about header files, separate-file compilation, and third-party libraries, it will feel more natural to revisit this content.

A complete CMake template explanation is provided later in the CMake Project Template. This chapter only focuses on two things:

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

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 will be 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 C++ development tools on Ubuntu or Fedora.
  2. Download the CMake template I've prepared.
  3. First, run the template as is to confirm the environment setup is fine.
  4. Check which files in the template are related to the subsequent learning.
  5. Debug the template program in VSCode by pressing F5.

Let me introduce a few names first, so they won't feel too sudden later:

NameLet's understand it this way first
g++the compiler that truly compiles C++ code
CMakeRead CMakeLists.txt, generate build rules
NinjaExecute compilation following the rules generated by CMake.
GDBDebugger, used when pressing F5 in VSCode
lib1 / lib2The two example libraries included in the template will remain unchanged in this chapter.
cmake_templateCurrent executable program name generated by the template

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

Install basic tools

Ubuntu / Debian

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

Eigen is installed here libeigen3-dev because the original template example used it. Once installed, the template will run directly.

Fedora

sudo dnf install git cmake ninja-build gcc gcc-c++ gdb eigen3-devel
Ubuntu/DebianFedora/RHELExplanation
gitgitversion control tools
cmakecmakeCMake build tool
ninja-buildninja-buildNinja build tool
gccgccC compiler
g++gcc-c++C++ compiler
gdbgdbGNU Debugger (GDB)
libeigen3-deveigen3-develEigen3 C++ Numerical Library Development Files

Check whether the tool is installed successfully

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

These commands all output version numbers, which indicates that the basic environment is already available.

Install VSCode

https://code.visualstudio.com/Download

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

After downloading, open your browser, locate the folder containing this installation package, and open a terminal in that path.

Debian-based: Enter sudo apt install ./code then press the tab key to autocomplete the filename, then press Enter.

RHEL series: Enter sudo dnf install ./code and then press the tab key to autocomplete the filename, then press Enter.

For example, after completion:

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

Configure VScode

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

code

Then you can set up an environment exclusively for C++ to avoid conflicts with the default environment.

alt text

Make some settings; just follow my lead.

alt text

Select the CMake configuration you created.

alt text

Install VSCode Extensions

Suggested extensions to install in VSCode:

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

Their respective roles are:

extendeffect
CMake ToolsIdentify CMakePresets.json, run configure/build, select the target, and manage the CMake project build process.
C/C++Microsoft's official C/C++ extension, offering core IntelliSense, breakpoint debugging, and GDB/LLDB debugging configuration support.
C/C++ DevToolsAuxiliary tools for C/C++ extensions, offering enhanced capabilities such as more convenient debug information display, memory/register/variable inspection, and other augmented features.
clangdBased on compile_commands.json to provide more accurate code completion, go-to definition, find references, diagnostic hints, and refactoring capabilities.

To put it simply,

  • CMake Tools is responsible for building the project;
  • C/C++ and C/C++ DevTools are primarily responsible for debugging;
  • clangd is mainly responsible for code hints, navigation, diagnostics, and refactoring.

If you're using clangd for code hints, I recommend turning off or toning down the IntelliSense of the C/C++ extension. This helps prevent duplicate or conflicting hints from two language servers running at the same time.

alt text

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 will be executed within this directory by default.

When you're just starting out, don't worry about Git history, nor rush into making a lot of file changes. The first step is just one single task: confirm that this template runs on your computer.

Select the CMake configuration you created.

alt text

First run the template as-is.

Run via command line

Don't rush to modify the code just yet. According to ctrl + ~, open the VSCode 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 looks like this:

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

alt text

Verify that the project, compiler, CMake, Ninja, and Eigen are all functioning properly. At this point, the most troublesome part of the environment setup has been successfully completed.

Note: During daily development, you can run programs from the build directory directly without needing to install each time.

Only during the verification of the installation layout is the following required:

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

When the following appears, it means success!

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

alt text

Run graphically using VScode.

We're going to run those commands above graphically using VScode:

Click the CMake on the left sidebar:

  1. First, you need to configure cmake --preset linux-debug, which is equivalent to clicking the Configure button in the interface and selecting Linux Debug:
    alt text
  2. Then this configuration for cmake --build --preset linux-debug will be automatically set up when you configure configure:
    alt text

Then you need to manually click the Build button in the lower-left corner to perform the build:

alt text

  1. Then ./build/linux-debug/src/cmake_template running this program is equivalent to:

First, configure the program path: alt text

Running the program: Debugging involves running a program in debug mode, whereas Launch directly executes the program without debugging. Unless you have specific debugging needs, it’s generally best to use Launch. alt text

![alt text](https://cdn.tungchiahui.cn/tungwebsite/assets/images/2023/10/05/1780707302786.webp)

In addition to the access points mentioned above, the VSCode bottom status bar also has Debug and Launch quick buttons next to the Build button. Once you've selected a cmake_template target and completed the build, you can directly click here to run or debug your program.

![alt text](https://cdn.tungchiahui.cn/tungwebsite/assets/images/2023/10/05/1780715507074.webp)

Next, I'll explain how to place the build output into install. Generally, you only use 'install' when you're preparing a program for release; for everyday use, just stick with the 'build' command above (remember to switch back to the build configuration after testing).

  1. cmake --install build/linux-debug is equivalent to: Press Ctrl+Shift+P in VSCode, then enter CMake: Install.
    alt text

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

  1. Then ./install/linux-debug/bin/cmake_template running this program is equivalent to: First, configure the program path:
    alt text

The way to run the program is the same as above, also by clicking Debug or Launch.

Template current structure

Now let's look at the relevant files in the template for this chapter. No need to understand every CMake option yet—just know that the code is located under src/.

.
├── CMakeLists.txt
├── CMakePresets.json
├── .vscode/
│   └── launch.json
├── cmake/
│   └── ProjectOptions.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 is:

positioneffect
src/main.cppProgram entry point, where execution begins at runtime.
src/lib1/Introductory Example Library
src/lib2/Second Example Small Library
CMakeLists.txtTell CMake how to build this project

This chapter only requires recognizing these positions; there is no need to modify them.

Frequently Asked Questions

Cannot find Ninja. This usually means the build system tool 'Ninja' is not installed or its path is not configured in your system environment. Please ensure it is installed and properly added to your PATH.

Error similar to:

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

Installation:

sudo apt install ninja-build

or

sudo dnf install ninja-build

Can't find gdb

If GDB is not found during debugging:

sudo apt install gdb

or

sudo dnf install gdb

我修改了 CMakeLists.txt 后,构建出现了问题。

This chapter does not require modifying CMakeLists.txt. If you later encounter build issues after modifying CMake files in subsequent chapters, you can re-run the configuration:

cmake --fresh --preset linux-debug

Or delete the build directory:

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

What should I learn next

This chapter simply gets you started with a functional, debuggable project.

The following chapters will start with the basics of C++ syntax.

  1. Introduction to C++ Basics
  2. Data Types and Data Storage
  3. Input and Output
  4. operator
  5. program flow structure

Starting from the next chapter, we'll only modify src/main.cpp first. When you learn about function separation into files, you can then organize lib1 / lib2; and when you learn about project organization, third-party libraries, and build systems, come back to review the CMake Project Template.

音乐页