build-hello-module-in-linux

编译简单的linux内核模块

hello.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/*
* a simple kernel module: hello
*
* Copyright (C) 2014 Barry Song (baohua@kernel.org)
*
* Licensed under GPLv2 or later.
*/

#include <linux/init.h>
#include <linux/module.h>

static int __init hello_init(void)
{
printk(KERN_INFO "Hello World in hjl's linux\n");
return 0;
}
module_init(hello_init);

static void __exit hello_exit(void)
{
printk(KERN_INFO "Hello World exit byebye\n ");
}
module_exit(hello_exit);

MODULE_AUTHOR("Hu Jinlei <hjl2016060203025@std.uestc.edu.cn>");
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("A simple Hello World Module");
MODULE_ALIAS("a simplest module");
  1. 编译
  2. insmod ./hello.ko加载
  3. rmmod hello卸载
  4. lsmod显示加载的模块

03-arm-linux-module.jpg

QEMU中运行编译的Linux内核

内核编译脚本 build.sh

1
2
3
4
5
6
7
8
9
10
export ARCH=arm
export EXTRADIR=${PWD}/extra
export CROSS_COMPILE=arm-linux-gnueabi-
make LDDD3_vexpress_defconfig
make zImage -j8
make modules -j8
make dtbs
cp arch/arm/boot/zImage extra/
cp arch/arm/boot/dts/*ca9.dtb extra/
cp .config extra/
  • 默认的内核配置文件为 LDDD3_vexpress_defconfig.上述脚本会将自动编译好的zImage,dtbs复制到extra目录中

  • extra目录下的vexpress是一张虚拟的SD卡,作为根文件系统的存放介质。它能以loop形式被挂载mount

    sudo mount -o loop,offset=$((2048*512)) extra/vexpress.img extra/img

编译模块的脚本 module.sh

1
2
3
4
make ARCH=arm CROSS_COMPILE=arm-linux-gnueabi- modules
sudo mount -o loop,offset=$((2048*512)) extra/vexpress.img extra/img
sudo make ARCH=arm CROSS_COMPILE=arm-linux-gnueabi- modules_install INSTALL_MOD_PATH=extra/img
sudo umount extra/img
  • 它会自动编译内核模块并安装到vexprees.img

启动带LCDARM Linux内 核

01-arm-linux-qemu-lcd.jpg

Author: hjl
Link: https://huqianshan.github.io/Linux/build-hello-module-in-linux/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.