Linux 最簡單核心模組 Hello World 樣本,linuxhello

來源:互聯網
上載者:User

Linux 最簡單核心模組 Hello World 樣本,linuxhello

註:如果想要按照本篇實踐,需要有能啟動並執行arm開發板和對應版本的核心(如果想在Linux主機上編譯運行,請參考文末附1)

1. 在相應版本核心的drivers目錄下建立如下檔案:

module file tree

其中檔案代碼如下:
/* hello.c */

#include <linux/init.h>#include <linux/module.h>static int hello_init(void){    printk(KERN_INFO "[init] Can you feel me?\n");    return 0;}static void hello_exit(void){    printk(KERN_INFO "[exit] Yes.\n");}module_init(hello_init);module_exit(hello_exit);MODULE_AUTHOR("Alan Wang <alan@wrcode.com>");MODULE_LICENSE("GPL");MODULE_DESCRIPTION("A simple Hello World Module");MODULE_ALIAS("A simple module");

/* Kconfig */

# drivers/alan_test/Kconfigmenu "ALAN_TEST Driver "comment "ALAN_TEST Driver comment"config ALAN_TEST    bool "ALAN_TEST support"config HELLO    tristate "hello module test"    depends on ALAN_TESTendmenu

/* Makefile */

# drivers/alan_test/Makefile# makefile for the ALAN_TESTobj-$(CONFIG_HELLO)    += hello.o
2. 修改上一級目錄的 Kconfig Makefie:

drivers 下的 Kconfig 末尾 endmenu 前添加一行

source "drivers/alan_test/Kconfig"endmenu

drivers 下的 Makefile 末尾加一行

obj-$(CONFIG_ALAN_TEST)        += alan_test/
3. make menuconfig 添加剛寫好的模組到核心:

依次是:Device Drivers —->
     ALAN_TEST Driver —->
       *** ALAN_TEST Driver comment ***
       [*] ALAN_TEST support
       < M > hello module test

退出儲存 menuconfig

4. 編譯核心:

使用 make 編譯
產生的 zImage (arch/arm/boot/zImage) 燒寫到開發板對應位置。
產生的 hello.ko(drivers/alan_test/hello.ko) 複製到開發板Linux系統的一個目錄下。

5. 插入核心模組:

insmod

6. 使用 modinfo 查看模組資訊:

modinfo

附1:編譯模組在PC上運行

把 hello.c 和 Makefile 放在同一目錄
/* Makefile */

KERNEL_VER = $(shell uname -r)# kernel modulesobj-m += hello.o# specify flags for the module compilationEXTRA_CFLAGS = -g -O0build: kernel_moduleskernel_modules:    make -C /lib/modules/$(KERNEL_VER)/build M=$(CURDIR) modulesclean:    make -C /lib/modules/$(KERNEL_VER)/build M=$(CURDIR) clean

編譯運行步驟如:
hello模組在PC上編譯運行

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.