将驱动程序编译进linux内核

  在linux驱动开发时,一般的做法是将驱动程序编译成.ko文件,然后使用“modprobe”命令将驱动模块加载到内核中。但在驱动开发完成后,就需要将驱动程序编译进Linux内核里面。

一、直接将驱动写死进linux内核

  1、以led字符设备驱动为例,首先在linux内核源码的/drivers/char/文件夹下创建一个mytest_led文件夹,将驱动文件存放在此文件夹下。
  2、修改/drivers/char/文件夹下的Makefile文件,添加一句:

obj-y				+= mytest_led/

  3、在/drivers/char/mytest_led文件夹下创建chardev_led.c文件和makefile文件。其中chardev_led.c文件存放驱动源代码。
  4、在/drivers/char/mytest_led/makefile文件下添加一句

obj-y				+= chardev_led.o

  5、编写好驱动文件chardev_led.c的内容后,重新编译即可将驱动编译进linux内核中。

二、定制驱动代码进linux内核

2.1、创建文件夹及文件

  1、在linux内核源码的/drivers/char/文件夹下创建一个mytest_led文件夹
  2、在/drivers/char/mytest_led文件夹下创建三个文件分别为
   ①、chardev_led.c文件
   ②、makefile文件
   ③、Kconfig文件

2.2、修改/drivers/char/文件夹下的makefile文件和Kconfig文件

  1、修改/drivers/char/文件夹下的Makefile文件,添加一句:

obj-y				+= mytest_led/

  2、修改/drivers/char/文件夹下的Kconfig文件,添加一句:

source "drivers/char/mytest_led/Kconfig"

2.3、编写/drivers/char/mytest_led文件夹下的makefile文件和Kconfig文件

  1、在/drivers/char/mytest_led/makefile文件下添加一句

obj-$(CONFIG_CHARDEV_LED)				+= chardev_led.o

  2、在/drivers/char/mytest_led/Kconfig文件下添加:

menu "mytest_led menu"

config CHARDEV_LED
	bool "This is my mytest_led config"
	default n
	help
		This is mytest_led!

endmenu 

  3、在chardev_led.c文件中编写驱动文件

2.4、选中驱动程序

2.4.1、通过make menuconfig选中

  在menuconfig菜单中进行配置,执行如下指令进行配置:

make menuconfig

  进入目录选项Device Driver --> Character devices—>mytest_led menu。然后按’y’选中“This is my mytest_led config”。保存退出,然后执行编译即可完成驱动编译进linux内核中。

2.4.2、通过xxx_defconfig配置文件选中

  在实际的工程中,通常已经有了配置文件xxx_defconfig,配置文件xxx_defconfig通常存放在/arch/arm/configs目录下。在配置内核时,使用命令“make xxx_defconfig”生成.config文件,进而配置linux内核。例如 Raspberry Pi 4 默认构建配置(32 位)时输入指令:

KERNEL=kernel7l
make bcm2711_defconfig

  如果应用make menuconfig指令重新配置内核则会破坏之前的配置选项。所以可以通过修改xxx_defconfig来进行选中驱动程序。
  在工程中所用的xxx_defconfig文件中添加一句:

CONFIG_CHARDEV_LED=y

  然后make xxx_defconfig,最后执行编译即可完成驱动编译进linux内核中。
  关于menuconfig的内容可以参考https://blog.csdn.net/xxxx123041/article/details/119951614

猜你喜欢

转载自blog.csdn.net/xxxx123041/article/details/120469497