获取编译命令

参考网上的步骤,在 chatgpt 的帮助下成功搭建了 kernel 的开发环境。

首先使用

uname -r

获取当前 WSL2 的内核版本,然后到 github 获取对应的 kernel 源码:
WSL2-Linux-Kernel
接下来安装必要的依赖:

sudo apt install make build-essential bear git bison build-essential flex libssl-dev libelf-dev libelf-dev build-essential pkg-config bc

将源码解压后,进入到源码根目录,准备编译:

zcat /proc/config.gz > .config
bear -- make -j $(nproc)

编译完成后,在源码根目录下会生成 compile_commands.json 文件。
除此之外,还可以使用内核自带的脚本,编译完成后直接在 kernel 源码根目录直接执行

python3 scripts/clang-tools/gen_compile_commands.py

接下来,用 vscode 打开源码根目录,安装 clangd 插件,把其他的 C 语言的插件暂时关掉。
安装完成后,创建 .vscode 文件夹,新建 c_cpp_properties.json 文件:

{
    "configurations": [
        {
            "name": "WSL",
            "includePath": [
                "${workspaceFolder}/**",
                "/usr/include/**",
                "/usr/local/include/**"
            ],
            "defines": [],
            "compilerPath": "/usr/bin/gcc",
            "cStandard": "c11",
            "cppStandard": "c++17",
            "intelliSenseMode": "linux-gcc-x64",
            "compileCommands": "${workspaceFolder}/compile_commands.json"
        }
    ],
    "version": 4
}

此外,由于 WSL2 没有自带内核头文件,可以生成然后安装一下:

make headers_install
sudo make headers_install INSTALL_HDR_PATH=/usr/local

生成完索引之后要注意的是,需要使用绝对路径打开项目文件夹(软连接也不行),否则还是会有一些小问题。

用 clangd 是为了更加准确地对源码进行分析,global 是对整个 linux 源码分析,会有跳转不准的情况。clangd 时,写代码时静态分析有些报错可能会不准确。

内核头文件

若只需要内核头文件,可以参考官方仓库里面有个 issue 的方法:

@raheel103 you need to match the headers with the current running kernel. The easy way is to get the WSL kernel source from https://github.com/microsoft/WSL2-Linux-Kernel/releases, run make headers_install and supply the correct INSTALL_HDR_PATH. It defaults to INSTALL_HDR_PATH=/usr so the kernel headers will be dropped in /usr/include. See details at https://www.kernel.org/doc/html/latest/kbuild/headers_install.html
You'll most likely need to build an external module, and the procedure is at https://www.kernel.org/doc/html/latest/kbuild/modules.html

ref

VScode 结合Global构建linux源代码阅读环境_klipper源代码 vscode-CSDN博客
VScode 结合clangd 构建linux源代码阅读环境_vscode编辑linux系统源代码-CSDN博客
WSL2-Linux-Kernel Headers · Issue #11557 · microsoft/WSL
Linux源码阅读(WSL2+VScode环境搭建)