Clangd with cross compile toolchain #
職業柄よくC/C++クロスコンパイラを使うのだが,Language ServerのClangdを使うと適切な型エイリアス等が解決されず困っていた.
VSCodeのIntelli Senseのノリで,compile_commands.jsonにクロスコンパイラを渡してあげたら勝手にincludeディレクトリ等を解決してくれると思っていたのだが,そうではなかったらしい.
クロスコンパイラから適切なヘッダを読み込むには,--query-driverオプションをclangdの呼び出し時に与える必要があるとのこと.
System headers
自分はNeoVimにMasonを導入してLSPを管理しているので,mason-lspconfigで設定する.
環境によってコンパイラのパスが違うので,上手いこと動的にフルパスを引っ張ってくるようにした(ロードが遅くなるのには目をつぶり…).
require("mason-lspconfig").setup_handlers({
...
["clangd"] = function()
-- Get cross compiler path for query driver
local cross_compilers = {
"riscv64-unknown-linux-gnu-gcc",
"riscv64-unknown-linux-gnu-g++",
}
local cross_compilers_path = {}
for _, val in ipairs(cross_compilers) do
local res = h.binary_path(val)
if res ~= nil then
table.insert(cross_compilers_path, res)
end
end
-- consruct clangd command args
local clangd_cmd = { "clangd" }
if next(cross_compilers_path) ~= nil then
local query_drivers = table.concat(cross_compilers_path, ",")
table.insert(clangd_cmd, "--query-driver=" .. query_drivers)
end
require("lspconfig").clangd.setup({
on_attach = on_attach,
capabilities = capabilities,
handlers = handlers,
cmd = clangd_cmd,
})
end,
})ドキュメントによると--query-driverはあくまでAllow Listで,compile_commands.json内でマッチするコンパイラが指定されていた場合に発動するらしい.
ポインタサイズが正しくとれてなくて,キャストするたびに警告吐かれてたのが消えてスッキリした.