编译一个linux内核模块

看源代码。

 

#include <linux/kernel.h> #include <linux/module.h> #if CONFIG_MODVERSIONS==1 #define MODVERSIONS #include <linux/modversions.h> #endif int init_module() { printk("Hello, I'm kernel/n"); return 0; } void cleanup_module() { printk("I'm kernel, bye/n"); }

 

再来看 makefile的写法

 

TARGET = hello
OBJS = hello.o
MDIR = drivers/misc

EXTRA_CFLAGS = -DEXPORT_SYMTAB
CURRENT = $(shell uname -r)
KDIR = /lib/modules/$(CURRENT)/build
PWD = $(shell pwd)
DEST = /lib/modules/$(CURRENT)/kernel/$(MDIR)

obj-m      := $(TARGET).o

default:
 make -C $(KDIR) SUBDIRS=$(PWD) modules

$(TARGET).o: $(OBJS)
 $(LD) $(LD_RFLAG) -r -o $@ $(OBJS)

ifneq (,$(findstring 2.4.,$(CURRENT)))
install:
 echo $(DEST) $(LD_RFLAG)
 su -c "cp -v $(TARGET).o $(DEST) && /sbin/depmod -a"
else
install:
 su -c "cp -v $(TARGET).ko $(DEST) && /sbin/depmod -a"
endif

clean:
 -rm -f *.o *.ko .*.cmd .*.flags *.mod.c

-include $(KDIR)/Rules.make

 

好了 放入到位置运行makefile即可

 

插入模块的命令是这样的

 

$insmod hello.ko(PS:尽管你看不到有.ko这样的文件,但是的确是这么来做的)

 

用 dmesg 就可以看到 输出啦。。。。

 

补充一个错误:

 

 

./linux/include/asm/elf.h: In function `start_ia32_thread':
./linux/include/asm/elf.h:153: warning: implicit declaration of function `load_g
s_index'
./linux/include/asm/elf.h: In function `elf_common_init':
./linux/include/asm/elf.h:166: error: structure has no member named `r8'
./linux/include/asm/elf.h:166: error: structure has no member named `r9'
./linux/include/asm/elf.h:166: error: structure has no member named `r10'
./linux/include/asm/elf.h:166: error: structure has no member named `r11'
./linux/include/asm/elf.h:167: error: structure has no member named `r12'
./linux/include/asm/elf.h:167: error: structure has no member named `r13'
./linux/include/asm/elf.h:167: error: structure has no member named `r14'
./linux/include/asm/elf.h:167: error: structure has no member named `r15'
In file included from ./linux/include/linux/module.h:21,
                 from hello.c:2:
./linux/include/asm/module.h:70:2: #error unknown processor family

 

可能路径显示不是这样 因为我是复制出来源代码来编译的,但是错误的确是这样。其实这个错误是makefile的问题,因为用

-Wall -DMODULE -D__KERNEL__ -D__SMT__ 的编译方法在kenel2.6下不行的。所以 按照上面写的makefile 就好了。。

 

你可能感兴趣的:(shell,function,Module,makefile,linux内核,structure)