linux最简单的驱动,一直编译有错误,改改停停,今天总算卖出了第一步。
1环境: vmware虚拟机中redhat9[linux-2.4.20-8]
2源码:
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
MODULE_LICENSE("GPL");
static int hello_init(void)
{
printk( "Hello, world/n");
return 0;
}
static void hello_exit(void)
{
printk( "Goodbye, cruel world/n");
}
module_init(hello_init);
module_exit(hello_exit);
3:编译:
这里,按照(ldd)书上写的用 gcc -c hello.c 确实可以编译通过,但是在insmod的时候,出现了如下的错误,hello.o: couldn't find the kernel version the module was compiled for 。再如何修改,也无法继续。于是改换思路。
谢了一个makefile
KERNELDIR:=/lib/modules/2.4.20-8/build
CFLAGS = -D_KERNEL_ -DMODULE -I $(KERMELDIR)/include -O
hello:hello.o
clean:
rm -rf *.o
这样make,居然产生error,不理解:
cc -D_KERNEL_ -DMODULE -I /include -O -c -o hello.o hello.c
cc hello.o -o hello
/usr/lib/gcc-lib/i386-redhat-linux/3.2.2/../../../crt1.o(.text+0x18): In function `_start':
../sysdeps/i386/elf/start.S:77: undefined reference to `main'
hello.o(.text+0xc): In function `init_module':
: undefined reference to `printk'
hello.o(.text+0x23): In function `cleanup_module':
: undefined reference to `printk'
collect2: ld returned 1 exit status
make: *** [hello] Error 1
但是已经生成了hello.o,insmod,居然可以安装,tail /var/log/message 居然有输出,但前面为何错误,一直不懂。
在看makefile的其编译语句,对其精简,即为gcc -D_KERNEL_ -DMODULE -c hello.c ,无错并可以正常insmod。
4:出的错误:
印象中还遇到了两个问题
1> 找不到insmod 命令,解决,在sbin下,用 /sbin/insmod
2>insmod时 出错
hello.o: kernel-module version mismatch
hello.o was compiled for kernel version 2.4.20
while this kernel is version 2.4.20-8.
忘了如何解决了,参考了如下的文章
http://topic.csdn.net/t/20041007/15/3431147.html
http://blog.chinaunix.net/u/21948/showart_240084.html
ok,做个小结,继续努力。