第一个内核驱动代码 hello, world!

 

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

static init __init hello_init(void)
{
  printk(KERN "Hello, world!");
  return 0;
}

static void __exit hello_exit(void)
{
  printk(KERN "Hello, exit!");
}

module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL");

 

 

$ cat Makefile
# 从终端启动编译
ifeq ($(KERNELRELEASE),)

        # 指定kernel源代码位置
        KERNELDIR ?= /home/deck/sn512/linux-7.0.12
        # 如果当前运行的内核就是要插入ko的内核
        # KERNELDIR ?= /lib/modules/$(shell uname -r)/build

        # 获取当前路径
        PWD := $(shell pwd)

modules:
        # 没有启动编译,只是切换到kernel源代码目录
        # M=$(PWD),告诉内核外部模块位置
        $(MAKE) -C $(KERNELDIR) M=$(PWD) modules

clean:
        rm -rf *.o *.ko *.mod

.PHONY: modules clean

# 从内核源代码启动编译
else
        # 定义编译目标,内核构建系统根据此值决定要编译的目标,并启动编译
        # obj-m,编译成模块ko
        # obj-y,编进 vmlinux
        obj-m := hello.o
endif

 

posted @ 2026-06-22 14:14  hhjyqj  阅读(0)  评论(0)    收藏  举报