Home > Software engineering >  kernel module doesn't search for include library when -I is used
kernel module doesn't search for include library when -I is used

Time:07-07

I want to build a basic main.c, that is actually a kernel module written in C. I have include header files that are in include/. I want to use GCC -I to make GCC search for the include headers in -Iinclude. However, GCC doesn't seem to understand that, and I have no clue how to debug it.

Tree:

main.c
include
   file.h

main.c

#include "file.h"
...

Makefile:

EXTRA_CFLAGS  = -Iinclude -Werror -Wall \
                -Wno-missing-braces -Wno-error=unused-function

all:
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules

clean:
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean

The error:

main.c: fatal error: file.h: No such file or directory

CodePudding user response:

That's because make is not actually running in your directory, when it compiles things.

The -C option in this command:

make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules

tells make to change it's current working directory to that path. Thus, include is no longer the include directory in your current directory.

You should write it like this:

EXTRA_CFLAGS  = -I'$M/include' -Werror -Wall \
                -Wno-missing-braces -Wno-error=unused-function

all:
        $(MAKE) -C "/lib/modules/$$(uname -r)/build" M='$(CURDIR)' modules

clean:
        $(MAKE) -C "/lib/modules/$$(uname -r)/build" M='$(CURDIR)' clean

You should always use $(MAKE), and never make, when running a sub-make. And using make's shell function is not really needed since a recipe is already running in a shell. And, PWD is just inherited from the calling shell and might be inaccurate.

  • Related