views:

1663

answers:

2

How to arrange a Makefile to compile a kernel module with multiple .c files?

Here is my current Makefile. It was auto generated by KDevelop

TARGET = nlb-driver
OBJS = nlb-driver.o
MDIR = drivers/misc

EXTRA_CFLAGS = -DEXPORT_SYMTAB
CURRENT = $(shell uname -r)
KDIR = /lib/modules/$(CURRENT)/build
PWD = $(shell pwd)
DEST = /lib/modules/$(CURRENT)/kernel/$(MDIR)

obj-m += $(TARGET).o

default:
    make -C $(KDIR) M=$(PWD) modules

$(TARGET).o: $(OBJS)
    $(LD) $(LD_RFLAG) -r -o $@ $(OBJS)

ifneq (,$(findstring 2.4.,$(CURRENT)))
install:
    su -c "cp -v $(TARGET).o $(DEST) && /sbin/depmod -a"
else
install:
    su -c "cp -v $(TARGET).ko $(DEST) && /sbin/depmod -a"
endif

clean:
    -rm -f *.o *.ko .*.cmd .*.flags *.mod.c
    make -C $(KDIR) M=$(PWD) clean

-include $(KDIR)/Rules.make
+2  A: 

I would assume that just listing more object files in the second line would do the trick.

unwind
+1  A: 

The dependencies for $(TARGET).o can be multiple object files, one for each source file in your driver. Many other drivers use the += operator after the initial declaration of OBJS. For example,

OBJS = nlb-driver.o
OBJS += file1.o
OBJS += file2.o
...

The target rule would then expand to be

$(TARGET).o: nlb-driver.o file1.o file2.o
    $(LD) $(LD_RFLAG) -r -o $@ $(OBJS)

This is nice if there are more source files than comfortably fit on a line. But if there are only a small number of files, you can also define all the objects on a single line

OBJS = nlb-driver.o file1.o file2.o
ctuffli