• Uncategorized

About c : Building-a-kernel-module-from-several-source-files-which-one-of-them-has-the-same-name-as-the-module

Question Detail

Is it possible to build a kernel module from several source files which one of them has the same name as the module?

For example:
I want to build “mymodule.ko” with the following source files:
mymodule.c
mymodule_func.c

This makefile doesn’t work:

#Makefile
obj-m += mymodule.o
mymodule-objs := mymodule.o mymodule_func.o

thanks

Question Answer

I found a solution, I placed my source file in a sub folder:

Makefile
src/mymodule.c
src/mymodule_func.c

#Makefile
obj-m += mymodule.o
mymodule-objs := ./src/mymodule.o ./src/mymodule_func.o

all:
    make -C $(KERNEL_PATH) M=$(PWD) modules

clean:
    make -C $(KERNEL_PATH) M=$(PWD) clean

Proper way to fix in kernel make file would be as:

# 
obj-m+= my_module.o

#append other source files except my_module.c which would be include by default
my_module-objs+= src1.o src2.o

As per my understanding it is not possible to have the module name and the source name to be the same. It would be better to provide module name as module.o and use the Makefile for compiling loadable kernel module as shown below,

Makefile

# If KERNELRELEASE is defined, we've been invoked from the
# kernel build system and can use its language.
ifneq ($(KERNELRELEASE),)
    **obj-m := module.o
        module-objs := mymodule.o mymodule_func.o**
    # Otherwise we were called directly from the command
    # line; invoke the kernel build system.
    EXTRA_CFLAGS += -DDEBUG
else
    KERNELDIR   := /lib/modules/$(shell uname -r)/build
    PWD         := $(shell pwd)
default:
    $(MAKE) -C $(KERNELDIR) M=$(PWD) modules
endif
clean: 
    $(MAKE) -C $(KERNELDIR) SUBDIRS=$(PWD) clean

You can use TARGET to name your .ko file as I did in this example:

TARGET = can

KDIR = /lib/modules/3.1.10-1.16-desktop/build
PWD := $(shell pwd)

obj-m += $(TARGET).o

can-objs := can_core.o can_open.o can_select.o can_sysctl.o can_write.o \
       can_close.o can_ioctl.o can_read.o can_util.o \
       can_debug.o can_error.o \
       can_async.o can_sim.o

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

So after the build I ended with a bunch of object files and can.ko

Another solution is create symlink to the file, say:

mymodule.c: ln -sf mymodule.c _mymodule.c

Now, use _mymodule.o as the object name:

mymodule-objs := _mymodule.o 

If anyone has stumbled upon this issue while working with Xilinx SoCs and petalinux, note the generated .bb (bitbake) file. Apart from specifying object files in the Makefile:

modulename-objs+= src1.o src2.o

all files (including headers) must be listed in the modulename.bb file’s SRC_URI variable.

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.