'Can not use clangd to read linux kernel code

I have some codes about Linux kernel driver. I use bear make to generate compile_commands.json.

this is some of my compile_commands.json:

"directory": "/usr/src/linux-headers-5.4.0-90-generic",
"file": "../../../home/ubuntu/programs/linuxKLearn/2/2.1/PrintingDriver/DriverFileOperations.c"

this is my Makefiles:

ifneq ($(KERNELRELEASE),)
    obj-m := PrintModule.o
    PrintModule-objs := DriverMain.o DriverFileOperations.o
EXTRA_CFLAGS := -DTEST_DEBUG -ggdb -O0
else
    KERNELDIR ?= /lib/modules/$(shell uname -r)/build
    PWD := $(shell pwd)
default:
    $(MAKE) -C $(KERNELDIR) M=$(PWD) modules
    rm *.order *.symvers *.mod.c *.o .*.o.cmd .*.cmd .tmp_versions -rf
endif

But when I use Vscode and clangd to read them, clangd shows that there is some problems when including <linux/mm.h>, the problems are as below:

Unknown argument: '-mno-fp-ret-in-387'
Unknown argument: '-mpreferred-stack-boundary=3'
Unknown argument: '-mskip-rax-setup'
Unknown argument: '-mindirect-branch=thunk-extern'
Unknown argument: '-mindirect-branch-register'
......

And clangd cannot find ssize_t. Unknown type name 'ssize_t'clang(unknown_typename) .the inode also has warning Declaration of 'struct inode' will not be visible outside of this functionclang(-Wvisibility),

How to fix include <linux/mm.h> and find ssize_t?

All help is welcome, thanks :)



Solution 1:[1]

What compiler did you use to build the code? I had the same issue, and building with Clang seemed to fix it. GCC and Clang have some options that are only implemented by one of the two compilers or options that are named differently, so clangd doesn't understand all the arguments used by GCC.

For example,

make CC=clang defconfig
make CC=clang

Or to cross compile:

make CC=clang ARCH=arm64 CROSS_COMPILE=aarch64-linux-gnu- defconfig
make CC=clang ARCH=arm64 CROSS_COMPILE=aarch64-linux-gnu-

Then you can run scripts/clang-tools/gen_compile_commands.py to generate a compile_commands.json. After restarting VSCode or clangd and opening a C file in the project, you should see the indexing begin again, and this time there shouldn't be any errors in the output and cross-references should work when it's finished.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 gsingh2011