gen_compile_commands.sh

下面是为你的项目结构 量身定制 的完整脚本:

它会扫描所有 .cpp 文件,添加正确的 -I 包含目录,输出符合 clangd 要求的 compile_commands.json 文件。


✅ 请将以下内容保存为 gen_compile_commands.sh

bash 复制代码
#!/bin/bash

# 项目根目录
PROJECT_DIR=$(pwd)

# 所有的头文件包含路径(根据你的 tree.txt 自动生成)
INCLUDES="-IAlarm/include \
-ICondition/include \
-IControl/include \
-ICore/include \
-IDataLog/include \
-IIO/include \
-IInterlock/include \
-IRecipe/include \
-IRemoteAccess/include \
-ISetup/include"

# 其他通用编译选项(根据你的 make.txt 提取)
CXXFLAGS="-Wall -Wextra -g -O0 -DDEBUG -fPIC -std=c++98"

# 开始生成 JSON 文件
echo "[" > compile_commands.json

# 标记是否是第一个条目(用于避免最后多逗号)
first=1

# 遍历所有 .cpp 文件
find . -name "*.cpp" | while read file; do
  # 添加逗号(跳过第一个)
  if [ $first -eq 0 ]; then
    echo "," >> compile_commands.json
  fi
  first=0

  echo "  {" >> compile_commands.json
  echo "    \"directory\": \"$PROJECT_DIR\"," >> compile_commands.json
  echo "    \"command\": \"g++ $CXXFLAGS $INCLUDES -c $file\"," >> compile_commands.json
  echo "    \"file\": \"$file\"" >> compile_commands.json
  echo -n "  }" >> compile_commands.json
done

# 结束 JSON
echo "" >> compile_commands.json
echo "]" >> compile_commands.json

echo "✅ compile_commands.json 生成完毕,共包含 $(grep -c 'file' compile_commands.json) 个源文件。"

✅ 使用方法

  1. 将脚本保存为:

    bash 复制代码
    gen_compile_commands.sh
  2. 加可执行权限:

    bash 复制代码
    chmod +x gen_compile_commands.sh
  3. 在项目根目录运行它:

    bash 复制代码
    ./gen_compile_commands.sh
  4. 会在当前目录生成:

    复制代码
    ./compile_commands.json

✅ clangd 就绪!

打开 Neovim,确认 clangd 可以正确跳转:

  • gd 跳转定义
  • gr 查找引用
  • K 查看文档
  • <C-Space> 补全提示

如需要,我还可以帮你配置 .clangd.clang-format 文件,是否需要?

相关推荐
Swizard1 天前
“这行命令跑了一晚,日志全丢了?”—— 5分钟彻底搞懂 Linux I/O 重定向与 tee 大法
shell
gis分享者1 天前
请解释 Shell 脚本中的位置参数(positional parameter)及其使用方法(中等)
shell·参数·使用·parameter·位置·positional
卡尔特斯2 天前
Zsh、GitBash 终端增强指南(Windows、Mac/Liunx)
shell
stella·3 天前
服务器割接,我所学习到的内容。
linux·运维·服务器·学习·shell·割接
柏木乃一4 天前
进程(7)命令行参数与环境变量
linux·服务器·shell·环境变量·鸣潮
Neolnfra4 天前
Shell攻防完全手册:从反弹到后渗透
渗透·shell·反弹shell
gis分享者6 天前
Bash 中如何使用正则表达式进行文本处理?(中等)
正则表达式·bash·shell·文本·处理
gis分享者7 天前
请编写一个 Bash 脚本检查系统中的所有服务状态(中等)
bash·shell·服务·状态·检查·所有
_OP_CHEN7 天前
【Linux系统编程】(十七)揭秘 Linux 进程创建与终止:从 fork 到 exit 的底层逻辑全解析
linux·运维·服务器·操作系统·shell·进程·进程创建与终止
pr_note8 天前
via ladder
shell·tcl