How to organize a makefile to compile a kernel module with multiple .c files?

How to organize a makefile to compile a kernel module with multiple .c files?

Here is my current Makefile. It was automatically created 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 
+7
linux module kernel makefile
source share
3 answers

I would suggest that simply listing more object files on the second line would do the trick.

+4
source share

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 OBJS declaration. For example,

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

Then the target rule will expand to

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

It is good if there are more source files than is convenient on line. But if there is only a small number of files, you can also define all objects in one line

 OBJS = nlb-driver.o file1.o file2.o 
+3
source share

In my case, the project consists of 6 files:

  • monter_main.c , monter_main.h
  • monter_cdev.c , monter_cdev.h
  • monter_pci.c , monter_pci.h

monter_main.c is the main file of my module.

Remember that you should not have a file with the same name as the module you are trying to build (for example, monter.c and monter.ko ) if you do not have all the code in this file.

Here are my makefiles:

  • Makefile

     KDIR ?= /lib/modules/`uname -r`/build default: $(MAKE) -C $(KDIR) M=$$PWD install: $(MAKE) -C $(KDIR) M=$$PWD modules_install clean: $(MAKE) -C $(KDIR) M=$$PWD clean 
  • Kbuild

     obj-m := monter.o monter-objs := monter_main.o monter_cdev.o monter_pci.o 
+1
source share

All Articles