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

时间:2013-12-10 06:19:04

标签: c++ c gcc makefile kernel-module

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 -shared -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 Destiny\n");
    c = myadd(1, 2);
    printk(KERN_ALERT "res is (%d)\n", c);
    return 0;
}

static void hello_exit(void)
{
printk(KERN_ALERT "goodbye,kernel\n");
}

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 

1 个答案:

答案 0 :(得分:1)

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