vscode c工程中抛弃C/C++ IntelliSense实现函数跳转
做c开发的程序员肯定被vscode函数跳转困扰,微软自带插件可以实现函数跳转,在十几个文件的小工程中还是挺好用,一旦文件数量有几百个几千个的时候,自带跳转功能就有点捉襟见肘了。
C/C++ IntelliSense插件有一下几个缺点:
1、只能适用小工程
2、调转速度非常慢,一直在检索
3、占用内存很大,内存莫名其妙被吃掉了
4、占用大量的c盘空间
以上几个问题,没有遇到说明工程很小,一旦工程数量变多,上面几个问题就会凸显。如何解决这些问题?
使用clangd
既然C/C++ IntelliSense插件有那么多问题,那么为何不直接抛弃,用一个更好的替代。没错clangd闪亮登场,这是谷歌llvm下的项目,在vscode中也有插件可以使用,
直接在扩展里面搜索clangd:
配置clangd
安装完成后并非万事大吉,这也是vscode的特殊所在,所有配置需要自己配置,也是让很多新手萌生退意,使用开箱即用的软件原因之一。
在安装完插件后,打开一个c文件,右下角弹出disable的选择点disable就行,关闭C/C++ IntelliSense的解析功能,或者打开设置,扩展->c/c+±>IntelliSense 选择disable
下载clangd二进制文件
clangd 还需要有后台服务支持,二进制文件到github上下载
https://github.com/clangd/clangd
选择对应的平台,ssh远程的选择linux,Windows上的选择clangd-windows-18.1.3.zip,这里不多赘述。解压到全英文路径上(很重要)。
还需要设置clangd路径 扩展->clangd->Clangd:Path
compile_commands.json 文件生成
还有最后一步 compile_commands.json 文件的生成,clangd依赖这个文件生成依赖文件。下面有几种生成改文件的方式
1、使用cmake的工程
cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=True ../
#cmake可以自动生成,将生成的文件拷贝到工程目录下。
2、linux下有多个命令可以使用
bear,compiledb都可以生成,仅支持linux下的环境
3、linux kernel代码
内核中有工具能生成,前提是内核已经编译过,这个工具依赖 编译生成的.cmd文件,工具说明如下:
$ python scripts/gen_compile_commands.py -h
usage: gen_compile_commands.py [-h] [-d DIRECTORY] [-o OUTPUT]
[--log_level LOG_LEVEL]
Creates a compile_commands.json database from kernel .cmd files
optional arguments:
-h, --help show this help message and exit
-d DIRECTORY, --directory DIRECTORY
Path to the kernel source directory to search
(defaults to the working directory)
-o OUTPUT, --output OUTPUT
The location to write compile_commands.json (defaults
to compile_commands.json in the search directory)
--log_level LOG_LEVEL
The level of log messages to produce (one of DEBUG,
INFO, WARNING, ERROR, CRITICAL; defaults to WARNING)
4、安卓aosp中
aosp也有类似的工具
aidegen frameworks/native/services -s -n -l c -r
export SOONG_GEN_COMPDB_DEBUG=1
python3 ./compext frameworks out/soong/development/ide/compdb/compile_commands.json ./compile_commands.json
其中compext内容为:
#!/usr/bin/python3
import sys
import json
import os
from pathlib import Path
if len(sys.argv) != 4:
print("Usage: python3 main.py <project directory> <input compiledb path> <output compiledb path>")
sys.exit()
files = Path(sys.argv[1])
result = list(map(os.path.realpath, map(str, list(files.rglob("*.cpp")) + list(files.rglob("*.c")))))
with open(sys.argv[2]) as compdb_input:
compdb_origin = json.load(compdb_input)
compdb_gen = []
for obj in compdb_origin:
full_path = obj["directory"] + '/' + obj["file"]
if full_path in result:
print("Find file: %s" % full_path)
compdb_gen.append(obj)
with open(sys.argv[3], "w") as compdb_out:
compdb_out.write(json.dumps(compdb_gen, indent=1))
5、还有一种,网上的代码,不可编译
这种情况是网上没有任何办法生成数据库文件,那么只能自己弄,用go写了个小工具compilejson
$ compilejson -h
Usage of compilejson:
-I value
外部include的文件夹
-cc string
-cc=gcc (default "gcc")
-m value
当前工作目录下有多个目录需要生成的使用-m包含
-size int
max file num, -size=4096 (default 16384)
-D
外部使用的宏定义,gcc编译器-D的参数
需要该工具的关注订阅号(技术分享猿),回复跳转获取
实现跳转
做完上述的步骤后需要重启clangd插件
shift+ctrl+p 打开vscode命令模式 输入clangd,找到restart
待解析完成后就能跳转,自动补齐等功能