linux下编写调用so文件学习

来源:互联网 发布:柠檬tv网络电视 编辑:程序博客网 时间:2024/05/18 20:07
主要参考的有:
1.http://topic.csdn.net/t/20051014/11/4326035.html这个帖子里面的如下部分
.so是Linux(Unix)下的动态链接库. 和.dll类似.

比如文件有: a.c, b.c, c.c
gcc -c a.c
gcc -c b.c
gcc -c c.c
gcc -shared libXXX.so a.o b.o c.o
要使用的话也很简单. 比如编译d.c, 使用到libXXX.so中的函数, libXXX.so地址是MYPATH
gcc d.c -o d -LMYPATH -lXXX
注意不是-llibXXX
2.http://blog.csdn.net/jenshy/article/details/674621这篇blog
3.http://blog.chinaunix.net/space.php?uid=13982689&do=blog&id=34335和这篇blog
============================================================================================
我有一个test.c文件和一个test.h,这两个文件要生成libsotest.so文件。然后我还有一个testso.c文件,在这个文件里面调用libsotest.so中的函数。
编写的过程中,首先是编译so文件,我没有编写makefile文件,而是参考的2里面说的直接写的gcc命令。
因为so文件里面没有main函数,所以是不可执行的,所以编译的时候要加上-c,只生成目标文件。
第一步是gcc test.c -c,生成test.o文件。
第二步是libsotest.so文件。
一开始的时候gcc  -shared libsotest.so test.o老是报错:gcc: libsotest.so: No such file or directory。后来想了一下,是因为没有指定文件名的原因,还是linux下c语言写的少了,经验太少。之后这样编译gcc  -shared -o libsotest.so  test.o 就通过了。
第三步就是在testso.c里面调用libsotest.so了。
程序的写法就是参照2这篇blog里面的程序写法来写的。只不过在testso.c里面我没有想blog里面那样再一次include so文件里面头文件(blog里面又一次include了datetime.h,而我没有include test.h)。
第四步编译testso.c
一开始老是报错error: ‘say’ undeclared (first use in this function)。后来看了一下dlsym函数,他返回的应该是一个只想函数的指针,而我定义say变量是一个void类型的指针,所以不行。
然后接着编译:gcc testso.c -o a.out -L ./ -l sotest
报错:
/tmp/cccq2Mq1.o: In function `main':
testso.c:(.text+0x2e): undefined reference to `dlopen'
testso.c:(.text+0x42): undefined reference to `dlerror'
testso.c:(.text+0x6d): undefined reference to `dlsym'
testso.c:(.text+0x75): undefined reference to `dlerror'
testso.c:(.text+0x89): undefined reference to `dlerror'
testso.c:(.text+0xb8): undefined reference to `dlclose'
collect2: ld returned 1 exit status
然后上网查找了一下,参照3这篇blog,这样编译gcc testso.c -o a.out -L ./ -ldl就过了。具体愿意不清楚,我采的原因是因为我已经在程序中制定了so文件的位置和文件名了,所以就不用-l来执行so的名字了。总之这些问题都是linux下c语言开发经验太少了。
之后运行编译完的程序,一切正常。
把代码贴上来,写的太烂了,只为了方便看这篇blog
test.h
  1. #include <stdio.h>

  2. void say(char *);
test.c
  1. #include "test.h"

  2. void say(char *word)
  3. {
  4.     printf("%s\n", word);
  5. }
testso.c
  1. #include <stdio.h>
  2. #include <dlfcn.h>
  3. #include <stdlib.h>

  4. main()
  5. {
  6.      void *dp;
  7.      char *error;
  8.      void (*say)(char*);
  9.      puts("so文件应用示范");
  10.      dp = dlopen("./libsotest.so", RTLD_LAZY);/*打开动态链接库*/
  11.      if(dp==NULL)
  12.      {
  13.          fputs(dlerror(), stderr);
  14.          exit(1);
  15.      }
  16.      say = dlsym(dp,"say");
  17.      error = dlerror();
  18.      if(dp==NULL)
  19.      {
  20.          fputs(dlerror(), stderr);
  21.          exit(1);
  22.      }
  23.      say("hello world");
  24.      dlclose(dp);
  25.      exit(0);
  26. }
原创粉丝点击