0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PlatformIOで `compile_commands.json` を生成してclangd(CursorなどのC++ LSP)に読み込ませるには

Posted at

PlatformIOでcompile_commands.jsonを生成してclangd(CursorなどのC++ LSP)に読み込ませるには、公式にサポートされているコマンドを使います。

具体的には、プロジェクトのルートで以下のコマンドを実行します。

pio run -t compiledb

このコマンドはビルド情報をもとに環境ごとにcompile_commands.jsonを自動生成します。通常は.pio/build/{env}/compile_commands.jsonのような場所に作成されるので、clangdが認識しやすい場所(プロジェクトルートなど)にコピーまたは移動して使うことが多いです。

生成をカスタマイズしたい場合

platformio.ini内で追加スクリプトを指定して、生成パスやツールチェインの設定を上書きできます。

例:

[env:myenv]
platform = ...
board = ...
extra_scripts = pre:extra_script.py

extra_script.pyの例:

import os
Import("env")

# ツールチェインのインクルードパスも含めて生成
env.Replace(COMPILATIONDB_INCLUDE_TOOLCHAIN=True)

# compile_commands.jsonの出力パスを変更
env.Replace(COMPILATIONDB_PATH=os.path.join("$BUILD_DIR", "compile_commands.json"))

こうすることで、pio run -t compiledb を走らせた際に、ビルドフォルダ内にcompile_commands.jsonが生成されます。

その後のclangd設定例

VS Codeなどのclangd用設定で、compile_commands.jsonのある場所を指定すると、LSPが正しく機能します。

例(settings.jsonなど):

"clangd.arguments": [
    "--compile-commands-dir=.pio/build/myenv"
]

あるいはcompile_commands.jsonをプロジェクトルートに移動し(もしくはシンボリックリンクを張り)、デフォルトの自動検出を使うのも一般的です。

要点をまとめると:

  • pio run -t compiledb でcompile_commands.jsonを生成
  • ファイルは .pio/build/{env}/compile_commands.json にできる
  • 必要ならplatformio.iniextra_scriptsで生成時のオプションをカスタマイズ可能
  • clangdの起動オプションかファイル場所を調整してLSPに認識させる

この方法がPlatformIOとclangd(CursorなどのC++ LSP)を連携させる標準的な流れです。

[1] https://github.com/platformio/platformio-vscode-ide/issues/1940
[2] https://community.platformio.org/t/how-can-i-generate-compile-commands-json-with-pio/26920
[3] https://community.platformio.org/t/errors-with-clangd-lsp-server-when-using-generated-compile-commands-json/24206
[4] https://github.com/platformio/platformio-core/issues/5209
[5] https://gist.github.com/neta540/9e65261be52d6cd4d6c17399b78d34bb?permalink_comment_id=3431406
[6] https://community.platformio.org/t/pio-build-and-compile-commands-json/7011/4
[7] https://docs.platformio.org/en/latest/integration/compile_commands.html
[8] https://aiotter.com/posts/m5stack-lsp/
[9] https://zenn.dev/potewo/scraps/497d766502bb5c
[10] https://discourse.nixos.org/t/how-to-automate-compile-commands-json-generation/54706

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?