如何将静态或共享库链接到内核模块

How to Link static or shared library to Kernel Module?

本文关键字:链接 内核模块 共享 静态      更新时间:2023-10-16

在aaa.c 中有一个函数

  int myadd(int a, int b){ 
        return a+b;
  }

并且使用将aaa.c构建到静态库中

gcc-c aaa.c-o aaa.o&ar-cr libaaa.a aaa.o

以及使用的共享库

gcc-c aaa.c-o aaa.o&gcc-共享-fPCI-o libaaa.so aaa.o

然后我编写了一个文件call.c,并尝试调用libaaa.so中的函数myadd(),但失败了。

,请给我一些建议

test.c:
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
MODULE_LICENSE("Dual BSD/GPL");
extern int myadd(int a, int b);
static int hello_init(void)
{
    int c = 0;
    printk(KERN_ALERT "hello,I am Destinyn");
    c = myadd(1, 2);
    printk(KERN_ALERT "res is (%d)n", c);
    return 0;
}
static void hello_exit(void)
{
printk(KERN_ALERT "goodbye,kerneln");
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_AUTHOR("Destiny");
MODULE_DESCRIPTION("This is a simple example!n");
MODULE_ALIAS("A simplest example");

这个Makefile将把两个c文件都放入call.ko中,它就可以工作了。但那不是我想要的。Makefile:

KVERSION = $(shell uname -r)
obj-m       = call.o
call-objs   = aaa.o test.o
Debug:
    make -C /lib/modules/$(KVERSION)/build M=$(PWD) modules
All:Debug
cleanDebug:
    make -C /lib/modules/$(KVERSION)/build M=/home/Destiny/myProject/kernel/cbtest/ clean
clean:cleanDebug
installDebug:Debug
    rmmod /lib/modules/2.6.18-348.12.1.el5/test/call.ko
    /bin/cp call.ko /lib/modules/$(KVERSION)/test/
    depmod -a
    insmod /lib/modules/2.6.18-348.12.1.el5/test/call.ko
install:installDebug
main.o : defs.h 

Ko文件在内核空间中运行,而不是在运行应用程序的用户空间中运行。Libc或Libc++等都是为用户空间应用程序准备的。所以你不能链接libc/c++函数,就像你不能链接内核中的任何libc函数一样。