Linux Kernel Source Auto Complete


To use lsp mode, we can use a file called compile_commands.json to tell lsp backends about file compile information.

Generate compile_commands.json

Either of following methods can generate compile_commands.json, Select as you like.

  • kernel script from scripts directory
    # after build kernel
    curl -fsSL\?h\=v5.3 | python
  • make bear
    1. install bear (Build EAR)
    2. compile you project
      • use bear to wrapper make command
    bear make -C kernel/msm-4.9 O=../../out/target/product/grus/obj/kernel/msm-4.9 DTC_EXT=dtc  ARCH=arm64 CROSS_COMPILE=aarch64-linux-android- KCFLAGS=-mno-android grus_debug_defconfig
    sed 's/..\/..\/..\/..\/..\/..\/..\/kernel\/msm-4.9\///g' compile_commands.json > kernel/msm-4.9/compile_commands.json

auto complete setup for Emacs

  • install ccls from
  • setup your emacs
    • default c-mode-hook will execute before local-variables loaded.
    • In the fellowing settings, we use hack-local-variables-hook to execute lsp-mode setting after local variables setting.
    • For some project, like Linux Kernel, we must exclude some args unrecognizable by clang.
    (use-package ccls
      :ensure t
          ;; Linux's gcc options. See ccls/wiki
          ["--param=allow-store-data-races=0" "-W*" "-f*" "-m*"]
          :extraArgs ["--gcc-toolchain=/usr"])
    (use-package lsp-mode
      :commands lsp
      (setq lsp-auto-guess-root t)    ; 我習慣自動選project root
      (setq lsp-enable-indentation nil)
      (setq lsp-enable-file-watchers nil)
      ;; (setq lsp-prefer-flymake t)  ; 預設t。flymake替代flycheck
      (require 'lsp-clients)          ; ocaml,css,python,bash,...
      (hack-local-variables . (lambda ()
                                (cond ((derived-mode-p 'c-mode 'c++-mode 'objc-mode)
                                         (require 'ccls)
    (use-package lsp-ui
      :commands lsp-ui-mode
      :ensure t
      :hook (lsp-mode . lsp-ui-mode))
    (use-package company-lsp
      :ensure t
      ;; 设置 company-lsp 为后端
      (push 'company-lsp company-backends))
  • dir-locals setting
    ;;; Directory Local Variables
    ;;; For more information see (info "(emacs) Directory Variables")
    ((nil .
          ((ccls-initialization-options . (:clang
                                            ;; Linux's gcc options. See ccls/wiki
                                            ["--param=allow-store-data-races=0" "-W*" "-f*" "-m*"])
                                           :compilationDatabaseDirectory "../out/target/product/qemu/KERNEL_OBJ"

enjoy codeing with emacs

Tags: Linux Kernel CodeComplete