1. 这个帖子里面的如下部分

.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. 这篇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.  
3. (char *);
 

  test.c 

 
1. #include "test.h"
2.  
3. (char *word)
4. {
5. ("%s\n", word);
6. }
 

  testso.c 

 
1. #include <stdio.h>
2. <dlfcn.h>
3. <stdlib.h>
4.  
5. ()
6. {
7. *dp;
8. *error;
9. (*say)(char *); 
10. ("so文件应用示范");
11. = dlopen("./libsotest.so", RTLD_LAZY); /*打开动态链接库*/
12. if(dp == NULL)
13. { 
14. (dlerror(), stderr);
15. exit(1);
16. } 
17. = dlsym(dp, "say");
18. error = dlerror();
19. if(dp == NULL)
20. { 
21. (dlerror(), stderr);
22. exit(1);
23. } 
24. ("hello world");
25. (dp);
26. exit(0);
27. }