[英]How to write a Linux kernel module makefile?
我正在嘗試編寫一個簡單的 hello world 內核模塊。 我在 Virtual Box 上使用 Ubuntu 18.04.2 LTS。 在 /usr/src 目錄中,我創建了一個名為 hello 的目錄,在該 hello 目錄中我創建了 hello.c 和一個 makefile。 這是我的生成文件:
obj-m += hello.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
當我執行命令“sudo make”時,我得到以下輸出:
make -C /lib/modules/5.3.0-28-generic/build M= modules
make[1]: Entering directory '/usr/src/linux-headers-5.3.0-28-generic'
make[2]: *** No rule to make target 'arch/x89/tools/relocs_32.c', needed by 'arch/x86/tools/relocs_32.o'. Stop.
arch/x86/Makefile:232: recipe for target 'archscripts' failed
make[1]: *** [archscripts] Error 2
make[1]: Leaving directory '/usr/src/linux-headers-5.3.0-28-generic'
makefile:4: recipe for target 'all' failed
make: *** [all] Error 2
我已經嘗試了我的 makefile 的一些變體,包括將“PWD”更改為“shell pwd”。 據我所知,我已經安裝了所有必要的工具和庫。 這里可能有什么問題?
變量PWD
由shell設置,因此您的 Makefile 依賴於從 shell 執行的make
調用,就像我們通常在終端中鍵入make
時make
那樣。
但是sudo make
從普通用戶環境執行make
。 此環境缺少PWD
變量,因此您的 Makefile 行為不正確。 這可以從您的輸出中找到:
make -C /lib/modules/5.3.0-28-generic/build M= modules
改用$(shell pwd)
表達式,它更可靠:
obj-m += hello.o
all:
make -C /lib/modules/$(shell uname -r)/build M=$(shell pwd) modules
clean:
make -C /lib/modules/$(shell uname -r)/build M=$(shell pwd) clean
或者,您可以使用以下方式以 root 權限調用make
:
sudo /bin/sh -c make
這種方式make
不是從普通的 root 環境執行,而是在一個中間 shell 下執行。 此外殼設置PWD
變量。
更新
正如@Ian Abbott 在評論中所指出的, $(PWD)
另一種選擇是$(CURDIR)
。 變量CURDIR
由make
本身設置(確切地說,由GNU Make)。 另請參閱該問題: bash: PWD 和 CURDIR 之間有什么區別? .
你的Makefile應該是這樣的
obj-m += hello.o
然后你的構建命令看起來像
make -C $KDIR M=$PWD
$KDIR是內核構建的源代碼樹。
就是這樣。 其余的由 kbuild 系統處理。
搭建off-tree模塊請參考官方文檔
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.