How to set up a development environment for Linux kernel with LSP support
We are going to set up a development environment for Linux kernel with LSP support. This will help you to write, navigate, and understand the kernel code more effectively. This is a follow-up to the contribute-kernel post where we set up a basic development environment for Linux kernel and talk about the process of contributing to the upstream.
Pre-requisites
We should first install clangd, which is a language server for C/C++ languages. It provides features like code completion, go to definition, find references, and more.
It can be easily installed on most Linux distributions. For example, on Ubuntu, you can install it using:
sudo apt install clangd
Generating compile_commands.json
This is the most important step in setting up the LSP support for the Linux kernel. The clangd
server uses a file called compile_commands.json
to understand how to compile the code. This file contains the compilation commands for each source file in the project.
For out-of-tree kernel modules
If we are developing out-of-tree kernel modules, we should use bear to help us generate this file. bear
is a tool that intercepts the compilation commands and generates the compile_commands.json
file.
We can install bear
using the package manager. For example, on Ubuntu, we can install it using:
sudo apt install bear -y
Then we can use bear
to generate the compile_commands.json
file by running the following command in the kernel source directory:
make clean
bear --append make
For in-tree kernel development
For in-tree kernel development, we can use the provided script scripts/clang-tools/gen_compile_commands.py
to generate the compile_commands.json
file. This script will generate the file based on the current kernel configuration.
We can run the following command in the kernel source directory after compilation:
python3 scripts/clang-tools/gen_compile_commands.py