1

I have a Makefile that compiles two Linux kernel modules (mod1.c and mod2.c).

obj-m = mod1.o mod2.o
KDIR=/lib/modules/$(shell uname -r)/build/
PWD=$(shell pwd)

# build the modules
default:
    $(MAKE) -C $(KDIR) M=$(PWD) modules

#cleanup
clean:
    rm -rf *.ko *.o *.mod* .*.cmd modules.order Module.symvers .tmp_versions

This works fine to build both kernel modules when I run make, but I would like to be able to specify which module to build. For example, make mod1 to compile mod1.c and make mod2 to compile mod2.c.

The thing that I am unsure of is how to handle obj-m. Otherwise, specifying which program to compile is well described online.

peachykeen
  • 4,143
  • 4
  • 30
  • 49
  • My make foo is a bit rusty, but I don't see where you ever reference/consume `obj-m`, so just delete the line entirely? You still need to add the two additional targets. – jwdonahue May 06 '20 at 17:30
  • Hi @jwdonahue thank you for the reply. That line is necessary (as far as I understand) as it tells the system to build `mod1.o` from `mod1.c`, and after linking, this will become `mod1.ko` (the same is true of `mod2.c`). Reference: https://www.kernel.org/doc/Documentation/kbuild/modules.txt – peachykeen May 06 '20 at 17:42
  • Then shouldn't it be `:=`? Or is the space around the equals symbol that makes it special in this variant of make? Like I said, I am rusty. – jwdonahue May 06 '20 at 17:53

1 Answers1

1

The kernel uses variables to set kernel modules on/off:

CROSS_COMPILE ?= /path/to/compiler/arm-linux-gnueabihf-
T1      ?= n
T2      ?= n

obj-$(T1) += test1.o
obj-$(T2) += test2.o
LINUX_SOURCE_DIR=/path/to/linux


all:
        $(MAKE) -C $(LINUX_SOURCE_DIR) M=$(PWD) modules ARCH=arm

test1:
        $(MAKE) T1=m

test2:
        $(MAKE) T2=m

clean:
        rm *o modules.order Module.symvers *mod.c

You can use this as make T1=m or make test2.

Bayou
  • 3,293
  • 1
  • 9
  • 22
  • I've played a lot with this some years ago and as far as I remember this is kind of your only option because it's parsed by "KConfig" before it's passed to "Make". Would love to see some attempts tho! – Bayou May 06 '20 at 18:12
  • This is neat. The `make T1=m` works for me, but `make test2` didn't seem to work. I get an error: `cc mod1.c -o mod1 mod1.c:1:24: fatal error: linux/init.h: No such file or directory compilation terminated.` – peachykeen May 06 '20 at 18:24
  • I've tested this by calling `make test1` in the same directory. Did you use `make -C /path/ test1` or something else? – Bayou May 07 '20 at 12:06
  • 2
    `CROSS_COMPILE` is not needed. One may specify it via command line. `LINUX_HEADERS` is a misleading name, it should be build folder. – 0andriy May 07 '20 at 18:07