clangd LSP
C/C++ language server integration providing comprehensive code intelligence through clangd (part of LLVM).
Capabilities
- - Code intelligence: Autocomplete, go-to-definition, find references
- Error detection: Real-time diagnostics for compilation errors
- Formatting: Code formatting with clang-format
- Refactoring: Rename symbols, extract function
- Supported extensions:
.c, .h, .cpp, .cc, .cxx, .hpp, .hxx, .C, INLINECODE8
Installation
Via Homebrew (macOS)
CODEBLOCK0
Via package manager (Linux)
CODEBLOCK1
Windows
CODEBLOCK2
Or download from LLVM releases.
Verify installation:
CODEBLOCK3
Usage
The language server runs automatically in LSP-compatible editors. For manual operations:
Compile
CODEBLOCK4
Format code
CODEBLOCK5
Static analysis
CODEBLOCK6
Configuration
Create .clangd in project root:
CODEBLOCK7
Or compile_commands.json for complex projects:
CODEBLOCK8
Integration Pattern
When editing C/C++ code:
- 1. clangd uses
compile_commands.json for project understanding - Run
clang-format to format code - Use
clang-tidy for static analysis - Compile with warnings enabled (
-Wall -Wextra)
Common Flags
Compile flags:
- -
-std=c++17 - C++17 standard - INLINECODE16 - Enable warnings
- INLINECODE17 - Optimization level
- INLINECODE18 - Debug symbols
- INLINECODE19 - Include path
- INLINECODE20 - Library path
clang-tidy checks:
CODEBLOCK9
More Information
clangd LSP
C/C++ 语言服务器集成,通过 clangd(LLVM 的一部分)提供全面的代码智能支持。
功能
- - 代码智能:自动补全、跳转到定义、查找引用
- 错误检测:编译错误的实时诊断
- 格式化:使用 clang-format 进行代码格式化
- 重构:重命名符号、提取函数
- 支持的扩展名:.c、.h、.cpp、.cc、.cxx、.hpp、.hxx、.C、.H
安装
通过 Homebrew(macOS)
bash
brew install llvm
添加到 PATH
export PATH=/opt/homebrew/opt/llvm/bin:$PATH
通过包管理器(Linux)
bash
Ubuntu/Debian
sudo apt install clangd
Fedora
sudo dnf install clang-tools-extra
Arch Linux
sudo pacman -S clang
Windows
bash
winget install LLVM.LLVM
或从 LLVM 发布页面 下载。
验证安装:
bash
clangd --version
使用
语言服务器在支持 LSP 的编辑器中自动运行。手动操作如下:
编译
bash
gcc file.c -o output # C
g++ file.cpp -o output # C++
clang file.c -o output # 使用 clang
格式化代码
bash
clang-format -i file.cpp
静态分析
bash
clang-tidy file.cpp -- -std=c++17
配置
在项目根目录创建 .clangd:
yaml
CompileFlags:
Add: [-std=c++17, -Wall, -Wextra]
Remove: [-W*]
Diagnostics:
UnusedIncludes: Strict
MissingIncludes: Strict
对于复杂项目,使用 compile_commands.json:
bash
cmake -DCMAKEEXPORTCOMPILE_COMMANDS=ON .
或
bear -- make
集成模式
编辑 C/C++ 代码时:
- 1. clangd 使用 compile_commands.json 理解项目
- 运行 clang-format 格式化代码
- 使用 clang-tidy 进行静态分析
- 启用警告编译(-Wall -Wextra)
常用标志
编译标志:
- - -std=c++17 - C++17 标准
- -Wall -Wextra - 启用警告
- -O2 - 优化级别
- -g - 调试符号
- -I<路径> - 包含路径
- -L<路径> - 库路径
clang-tidy 检查:
bash
clang-tidy file.cpp --checks=* --
clang-tidy file.cpp --fix -- # 自动修复
更多信息