恩,多是我比较愚钝,一个内核编译搞了一天,各类问题,各类bug,几度无奈,也是由于我突发奇想,并无按照原来的那种操做,我直接把helloworld程序放到内核模块中编译成了一个驱动程序,虽然其中遇到了不知道多少的问题,不过最终是个完美的结局,给本身点个赞!
好了,废话很少说,直接开始还原个人helloworld驱动内核程序编译流程。linux
编译内核,首先要作的就是有一个内核可以供你编译,我选择的操做系统是Ubuntu14.04,低版本的系统的编译难度要小不少,因此固然要选个简单的了。内核是在官网中直接下载的,网址以下:https://www.kernel.org/git
版本我选择的是3.16.50,这里咱们要选择一个与当前内核版本相近的内核。
内核完成下载之后,首先用su命令启动管理员权限,接着将内核压缩包移动至/root文件夹下,并将linux-3.16.50压缩文件解压到/usr/src目录下。github
1.新建文件
首先,新建一个名为helloworld的文件夹,接着在文件夹内新建helloworld.c文件,c语言程序的内容以下:sql
#include <linux/module.h>
#include <linux/kernel.h>
int init_hello_module(void)
{
printk("***************Start***************\n");
printk("Hello World! Start of hello world module!\n");
return 0;
}
void exit_hello_module(void)
{
printk("***************End***************\n");
printk("Hello World! End of hello world module!\n");
}
MODULE_LICENSE("Dual BSD/GPL");
module_init(init_hello_module);
module_exit(exit_hello_module);
随后,再在文件夹内新建一个Makefile文件,文件的内容是shell
obj-$(CONFIG_HELLOWORLD)+=helloworld.o
这时候,执行编译命令后,就会自动进入该目录下,而且会将helloworld.c编译成helloworld.o。
继续,在该文件夹下新建一个Kconfig文件,添加代码:bash
menu "helloworld driver"
config HELLOWORLD
tristate"HELLOWORLD"
default y
---help---
Say 'Y' here, it will be compiled into thekernel; If you choose 'M', it will be compiled into a module named ashelloworld.ko.
endmenu
注意:help下面的文字千万不能添加空格,不然在后续操做当中会出现问题,会报错
最后,将helloworld文件夹总体移动到/src/linux-xxxx/drivers目录下。微信
2.修改文件
首先,修改/usr/src/linux-xxxx/drivers目录下的Kconfig文件,在endmenu以前添加一条语句:ui
source "drivers/helloworld/Kconfig"
很明显,这里的做用是引用刚刚咱们新建的Kconfig文件,或者更标准一点的用语是挂载。
其次,修改/drivers目录下的Makefile文件,添加:spa
obj-$(CONFIG_HELLOWORLD) += helloworld/
这行编译指令告诉模块构建系统在编译模块时须要进入 helloworld/ 子目录中。此时的驱动程序的编译取决于一个特殊配置 CONFIG_HELLOWORLD配置选项。
最后,修改arch/arm目录下的Kconfig文件,在menu “Device Drivers……endmenu”或者其余相似的地方直接添加语句:操作系统
source "drivers/helloworld/Kconfig"
因为咱们是将这个程序的当作驱动程序来启动,因此在执行命令:
make menuconfig
后,在DeviceDrivers菜单下选择helloworld驱动,按空格键将选项前面的标志调整为[*]便可。
使用命令:make -j2
,
2表明的是编译的速度,为了加快速度,咱们这里选择2,你能够自行选择,但也不要过高。
大约在虚拟机编译下两个小时左右,编译工做就完成了。
使用命令:
make modules
,模块编译
make modules_install
安装模块
make install
最后安装内核
grub就是管理Ubuntu系统启动的一个程序,咱们编译好的内核要运行就要修改对应的grub,其实很简单。
mkinitramfs 3.16.50 -o /boot/initrd.img-3.16.50
update-grub2
update-grub2命令会帮咱们自动修改grub
最后,重启选择新编译的内核就ok啦!
感谢您的阅读,欢迎指正博客中存在的问题,也能够跟我联系,一块儿进步,一块儿交流!
微信公众号:进击的程序狗
邮箱:roobtyan@outlook.com
我的博客:https://roobtyan.github.io