Linux module compilation: two methods detailed explanation

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-mthe variable specifies the module file to compile (here mymodule.o). allThe target uses makethe command to call the directory in the kernel source tree build, and uses Mparameters to specify the directory where the module source code is located, and then executes modulesthe command to compile the module. cleanThe target also uses makecommands, but executes cleancommands to clean the files generated by compilation.

In the module source code directory, execute makethe command to compile the module. After successful compilation, a .kofile will be generated and insmodthe module can be loaded using the command.

Method 2: Compile using gcc

Guess you like

Origin blog.csdn.net/Book_Sea/article/details/133494650