Open4

MacOS + neovim + coc で ccls (C/C++ language server)を動かす

moss0321moss0321

homebrew 経由で clang を入れている場合、headerファイルの配置が通常と異なるらしいので
以下のコマンドで配置を調べる。

clang++ -xc++ -fsyntax-only -v /dev/null

出力結果に以下のような部分があるので控えておく

 /usr/local/include
 /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1
 /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/12.0.0/include
 /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include
 /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include
 /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks (framework directory)

ref: https://github.com/MaskRay/ccls/wiki/Build#macos

moss0321moss0321

CocConfigを開き、languageServer に以下のようにcclsの設定を記述。

{
  "languageServer": {
    "ccls": {
      "command": "ccls",
      "filetypes": ["c", "cpp", "objc", "objcpp"],
      "rootPatterns": [
        ".ccls-root",
        "compile_commands.json",
        ".vim/",
        ".git/",
        ".hg/"
      ],
      "initializationOptions": {
        "cache": {
          "directory": "/tmp/ccls"
        },
        "clang": {
          "resourceDir": "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/12.0.0/include",
          "extraArgs": [
            "-isystem/usr/local/include",
            "-isystem/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1",
            "-isystem/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/12.0.0/include",
            "-isystem/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include",
            "-isystem/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include",
            "-isystem/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks"
          ]
        }
      }
    }
  }
}

注意点としては、clang.extracArgs に先程控えた ヘッダファイルの配置を記入する。
その際 -isystem を先頭につける。

これがないと ccls がヘッダファイルを見つけられず

#include <stdio.h>

のような記述がエディタ上でのみnot foundエラーになる。

moss0321moss0321

compilerの設定情報をcclsに教えて上げる必要があるので、compile_command.json というファイルをプロジェクトルートに作成したい

以下のようなファイルになる。

[
  {
    "arguments": [
      "/usr/bin/clang",
      "-c",
      "-o",
      "./build/kilo",
      "kilo.c"
    ],
    "directory": "/Users/moss0321/dev/projects/kilo",
    "file": "/Users/moss0321/dev/projects/kilo/kilo.c",
    "output": "/Users/moss0321/dev/projects/kilo/./build/kilo"
  }
]

このファイルを手動で作成するのは面倒なので、bare という ツールを使う

brew install bare

bare の 引数にコンパイル用のコマンドを渡してあげると自動で compile_command.json生成してくれる。

適当にMakefileにビルドコマンドを定義して

hello:
    	clang hello.c -o ./build/hello

bare に渡す

bare -- make

comipile_command.json が生成されている