Linux驅動開發: Ubuntu(PC機)系統上編譯驅動並載入測試

DS小龍哥發表於2021-01-03

一、環境介紹

作業系統: ubuntu18.04 64位

二、編寫Makefile(PC機)

先輸入uname -r命令檢視當前系統的版本.

root@wbyq:/mnt/hgfs/linux-share-dir/linux_c/usb_dev_ubuntu# uname -r
5.3.0-40-generic

檢視系統核心的路徑是否存在:

root@wbyq:/mnt/hgfs/linux-share-dir/linux_c/usb_dev_ubuntu# ls /usr/src/
linux-headers-5.3.0-40          linux-headers-5.4.0-53-generic  linux-hwe-5.4-headers-5.4.0-47
linux-headers-5.3.0-40-generic  linux-hwe-5.4-headers-5.4.0-42  linux-hwe-5.4-headers-5.4.0-48
linux-headers-5.4.0-48-generic  linux-hwe-5.4-headers-5.4.0-45  linux-hwe-5.4-headers-5.4.0-53

根據當前系統的版本,確定對應的路徑:  /usr/src/linux-headers-5.3.0-40

root@wbyq:/mnt/hgfs/linux-share-dir/linux_c/usb_dev_ubuntu# ls /usr/src/
linux-headers-5.3.0-40          linux-headers-5.4.0-53-generic  linux-hwe-5.4-headers-5.4.0-47
linux-headers-5.3.0-40-generic  linux-hwe-5.4-headers-5.4.0-42  linux-hwe-5.4-headers-5.4.0-48
linux-headers-5.4.0-48-generic  linux-hwe-5.4-headers-5.4.0-45  linux-hwe-5.4-headers-5.4.0-53
root@wbyq:/mnt/hgfs/linux-share-dir/linux_c/usb_dev_ubuntu# ls /usr/src/linux-headers-5.3.0-40
arch   certs   Documentation  fs       init  Kbuild   kernel  Makefile  net      scripts   sound  ubuntu  virt
block  crypto  drivers        include  ipc   Kconfig  lib     mm        samples  security  tools  usr

完整的編寫Makefile如下:

Linux_ADD=/usr/src/linux-headers-5.3.0-40-generic
app_dev:
	make -C $(Linux_ADD) M=`pwd` modules clean
	make -C $(Linux_ADD) M=`pwd` modules
	gcc spectrometer_app.c -o app
obj-m +=spectrometer_usb_drv.o

編譯安裝測試:

root@wbyq:/mnt/hgfs/linux-share-dir/linux_c/usb_dev_ubuntu# insmod spectrometer_usb_drv.ko 
root@wbyq:/mnt/hgfs/linux-share-dir/linux_c/usb_dev_ubuntu# modinfo spectrometer_usb_drv.ko 
filename:       /mnt/hgfs/linux-share-dir/linux_c/usb_dev_ubuntu/spectrometer_usb_drv.ko
license:        GPL
author:         xiaolong
srcversion:     40F0CA1A1C1E3BA787F1B57
alias:          usb:v0661p294Bd*dc*dsc*dp*ic*isc*ip*in*
alias:          usb:v148Fp5370d*dc*dsc*dp*ic*isc*ip*in*
depends:        
retpoline:      Y
name:           spectrometer_usb_drv
vermagic:       5.3.0-40-generic SMP mod_unload 
root@wbyq:/mnt/hgfs/linux-share-dir/linux_c/usb_dev_ubuntu# rmmod spectrometer_usb_drv.ko 

 

三、順便說下嵌入式Linux驅動Makefile編譯方式

Linux_ADD=/home/wbyq/work/linux-3.5/linux-3.5
app_dev:
	make -C $(Linux_ADD) M=`pwd` modules clean
	make -C $(Linux_ADD) M=`pwd` modules
	cp *.ko /home/wbyq/project/ -fv
	arm-linux-gcc spectrometer_app.c -o app
	cp app /home/wbyq/project/ -fv
obj-m +=spectrometer_usb_drv.o

 

 

 

 

相關文章