有时需要 compile_commands.json 文件为 Clangd 提供信息,使用 CMake 生成的 compile_commands.json 文件当中,可能存在 Clangd 无法解析的命令参数(如 --mno-direct-extern-access
)。这是因为 CMake 默认实用的编译器(如 gcc )的有些参数 clang 并不支持。
解决方案一 : CMake 使用 Clang 作为编译器
- 在
cmake
命令后附加-DCMAKE_CXX_COMPILER=clang -DCMAKE_C_COMPILER=clang
; - 或者在 CMakeLists.txt 文件中添加
这两行代码应仅次于set(CMAKE_C_COMPILER clang) set(CMAKE_CXX_COMPILER clang)
cmake_minimum_required
,否则可能无效。
解决方案二 : 使用 “.clangd” 文件忽略无法识别的参数
内容如下:
CompileFlags:
Remove: [--mno-direct-extern-access]
较为全面的如下:
CompileFlags:
Remove: [-mno-direct-extern-access, -fconserve-stack, -fno-allow-store-data-races, -mfunction-return=thunk-extern, -mindirect-branch-cs-prefix, -mindirect-branch-register, -mindirect-branch=thunk-extern, -mskip-rax-setup, -mpreferred-stack-boundary=3, -mno-fp-ret-in-387]
参考文献:
stackoverflow : Can not use clangd to read linux kernel code