In Linux systems, modules are blocks of code that can be dynamically loaded and unloaded, and they extend the functionality of the kernel. Writing and compiling Linux modules is a key step in kernel extension and driver development. This article will introduce the two compilation methods of Linux modules in detail and provide corresponding source code examples.
Method 1: Compile using Makefile
Using Makefiles is a common way of compiling Linux modules. A Makefile is a text file that contains the instructions needed to compile and link a module. Here is a simple Makefile example:
obj-m += mymodule.o
all:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
In the example above, obj-m
the variable specifies the module file to compile (here mymodule.o
). all
The target uses make
the command to call the directory in the kernel source tree build
, and uses M
parameters to specify the directory where the module source code is located, and then executes modules
the command to compile the module. clean
The target also uses make
commands, but executes clean
commands to clean the files generated by compilation.
In the module source code directory, execute make
the command to compile the module. After successful compilation, a .ko
file will be generated and insmod
the module can be loaded using the command.
Method 2: Compile using gcc