天天看點

linux編譯c成ko,作業系統 - Linux編譯一個簡單的ko子產品

本來打算寫一個簡單的demo去驗證sipn_lock、mutex_lock死鎖的,

結果代碼寫好了,忘了怎麼編譯成ko了...

還是自己手動記一下,友善以後找資料。

(有很多的部落格其實主要内容都是别人的,自己隻是照着做了一遍,然後把其中的試錯都記錄下來,防止下一次再用時再出錯)

不廢話,直接照做:

寫一個.c代碼

//下面是驅動源代碼

#include #include static int hello_init(void)

{

printk("Hello, World !\n");

return 0;

}

static void hello_exit(void)

{

printk("Goodbye, World !\n");

}

module_init(hello_init);

module_exit(hello_exit);

MODULE_LICENSE("Dual BSD/GPL");

寫一個Makefile檔案

//下面是Makefile代碼

#!/bin/bash

#通知編譯器我們要編譯子產品的哪些源碼

#這裡是編譯 hello.c這個檔案編譯成中間檔案 hello.o

obj-m := hello.o

#聲明目前的架構,這裡使用者需要根據實際情況選擇架構類型

export ARCH=arm

#聲明交叉編譯工具鍊,這裡使用者需要根據實際情況選擇對應的工具鍊

export CROSS_COMPILE=arm-himix200-linux-

#源碼目錄變量,這裡使用者需要根據實際情況選擇路徑

#下面作者是将Linux的源碼目錄

KERDIR := /home1/zhugeyifan/source/K5/3519av100/packages/linux_lsp/kernel/linux-4.9.37/

#目前目錄變量

CURDIR := $(shell pwd)

#make命名預設尋找第一個目标

#make -C就是指調用執行的路徑

#$(KERDIR)Linux源碼目錄,作者這裡指的是.../linux-4.9.37/

#$(CURDIR)目前目錄變量

#modules要執行的操作

#注意!假如複制到Makefile後,下行提示紅色,把 all:下面一行的make前面的空格删除後添加(Tab)制表符

all:

make -C $(KERDIR) M=$(CURDIR) modules

#make clean執行的操作是删除字尾為o的檔案

#注意!假如複制到Makefile後,下行提示紅色,把 clean:下面一行的make前面的空格删除後添加(Tab)制表符

clean:

make -C $(KERDIR) M=$(CURDIR) clean

編譯

直接執行make,編譯生成ko子產品

作者有遇到如下報錯:

make -C /home1/zhugeyifan/source/K5/3519av100/packages/linux_lsp/kernel/linux-4.9.37/ M=/home1/zhugeyifan/source/K5/3519av100/packages/linux_lsp/kernel/test_ko/hello modules

make[1]: Entering directory `/home1/zhugeyifan/source/K5/3519av100/packages/linux_lsp/kernel/linux-4.9.37'

ERROR: Kernel configuration is invalid.

include/generated/autoconf.h or include/config/auto.conf are missing.

Run 'make oldconfig && make prepare' on kernel src to fix it.

WARNING: Symbol version dump ./Module.symvers

is missing; modules will have no dependencies and modversions.

CC [M] /home1/zhugeyifan/source/K5/3519av100/packages/linux_lsp/kernel/test_ko/hello/hello.o

In file included from :0:0:

././include/linux/kconfig.h:4:32: fatal error: generated/autoconf.h: No such file or directory

#include ^

compilation terminated.

make[2]: *** [/home1/zhugeyifan/source/K5/3519av100/packages/linux_lsp/kernel/test_ko/hello/hello.o] Error 1

make[1]: *** [_module_/home1/zhugeyifan/source/K5/3519av100/packages/linux_lsp/kernel/test_ko/hello] Error 2

make[1]: Leaving directory `/home1/zhugeyifan/source/K5/3519av100/packages/linux_lsp/kernel/linux-4.9.37'

make: *** [all] Error 2

原因是核心沒有編譯,先處理核心編譯

生成

編譯成功後,生成檔案如下:

[email protected]:~/hello/ls

hello.c hello.ko hello.mod.c hello.mod.o hello.o Makefile modules.order Module.symvers

參考資料

ERROR: Kernel configuration is invalid.

hello.ko---Makefile

Linux下hello.ko核心子產品制作的全過程