Linux out of tree module build issue

2019-08-15 13:36发布

问题:

obj-m := $(MODNAME).o
ccflags-y := $(CCFLAGS)
src_files := $(wildcard $(foreach pat,*.c *.cpp *.s,src/$(pat) src/$(MODNAME)/$(pat)))
$(MODNAME)-objs := $(addsuffix .o, $(basename $(src_files)))

all:

    make -C $(KDIR) M=$(shell pwd) modules

clean:

    make -C $(KDIR) M=$(shell pwd) clean

I have this make file for building kernel modules. However whenever I run it, I get an error saying that there is no rule to make target .c. .c is not a source file. If I remove the "if [ -d src ]" check then I get an error saying src doesn't exists on the recursive make call from the kernel build system. If I specify the full path to src it gives the same output saying that it can't find it (which is really weird). If I hard code src_files it works (if I didn't copy and paste wrong). Does anybody have any idea what is going on?

回答1:

In your makefile you expect current directory to be the one contained given makefile. But when your file is executed from Kbuild context, this is no longer true: current directory is directory with kernel sources.

That is why content of src_files variable becomes wrong: wildcard cannot find files under src/ in kernel sources. You may use special src variable for refer to directory with your makefile:

src_files := $(wildcard $(foreach pat,*.c *.cpp *.s,$(src)/src/$(pat) $(src)/src/$(MODNAME)/$(pat)))

From the other side, paths enumerated in *-objs variable should be relative (this is requirement by Kbuild). So you need to strip prefix from these absolute paths:

src_files_rel := $(src_files:$(src)/%=%)

Then you may use these paths for create objects list:

$(MODNAME)-objs := $(addsuffix .o, $(basename $(src_files_rel)))