如何使用 zed editor 编译 c++ 程序?

如何使用 zed editor 编译 c++ 程序?

Zed 是一款由 Atom 和 Tree-sitter 的创作者开发的高性能、多人在线代码编辑器。它旨在让你以思维的速度编写代码,提供流畅、高效的编码体验。Zed 的设计注重性能和协作,支持多人实时编辑同一文件,非常适合团队开发和远程协作。此外,Zed 还集成了强大的代码分析工具,帮助开发者更快地发现和修复问题。无论是个人开发者还是团队,Zed 都是一个值得尝试的现代代码编辑器。

目录结构

cpp project 结构如下所示:

├── CMakeLists.txt
├── build
│   ├── CMakeCache.txt
│   ├── CMakeFiles
│   ├── Makefile
│   ├── cmake_install.cmake
│   ├── compile_commands.json
│   └── main
├── compile.sh
└── source
    └── main.cpp

文件内容

main.cpp

#include <print>
int main() {
    
    
  std::println("Hello World!");
  return 0;
}

CMakeLists.txt

cmake_minimum_required(VERSION 3.10)
project(cpp)

# This option is used to enable the export of compile commands, which can be useful for testing or debugging purposes.
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

# This sets the standard version of C++ that should be used in the project. In this case, it's set to C++23.
set(CMAKE_CXX_STANDARD 23)

# This option tells CMake to enforce the specified standard version for all source files in the project.
set(CMAKE_CXX_STANDARD_REQUIRED ON)

# This option disables the use of extensions that are not part of the standard C++ language.
set(CMAKE_CXX_EXTENSIONS OFF)

# This sets the compiler to be used for C programs in the project, which is clang in this case.
set(CMAKE_C_COMPILER "/usr/bin/clang")

# This sets the compiler to be used for C++ programs in the project, which is also clang++.
set(CMAKE_CXX_COMPILER "/usr/bin/clang++")

# This command tells CMake to create a new executable from the main.cpp file in the source directory.
add_executable(main source/main.cpp)

.zed/settings.json
运行 which clangd 查看位置

{
    
    
  "enable_language_server": true,
  "format_on_save": "on",
  "formatter": "language_server",
  "inlay_hints": {
    
    
    "enabled": true,
    "show_type_hints": true,
    "show_parameter_hints": true,
    "show_other_hints": true
  },
  "lsp": {
    
    
    "clangd": {
    
    
      "binary": {
    
    
        "path": "/usr/bin/clangd",
        "arguments": [
          "--background-index",
          "--compile-commands-dir=build"
        ]
      }
    }
  }
}

clangd 指定了编译指令的目录为 --compile-commands-dir=build,在前面 CMakeLists.txt 中使用到了
CMAKE_EXPORT_COMPILE_COMMANDS ,该选项会导出编译命令,用来给 clangd 语法分析使用.

编译 & 运行

cd build
cmake .. && make && ./main

输出如下:

-- Configuring done (0.0s)
-- Generating done (0.0s)
-- Build files have been written to: /Users/cheungxiongwei/cpp/build
[ 50%] Building CXX object CMakeFiles/main.dir/source/main.cpp.o
[100%] Linking CXX executable main
[100%] Built target main
Hello World

额外补充

使用 clang++ 直接编译 main.cpp,为了便于使用可在工程目录编写一个 complile.sh 脚本.

complile.sh

clang++ -std=c++2b -o build/main source/main.cpp && ./build/main

猜你喜欢

转载自blog.csdn.net/cheungxiongwei/article/details/142792937