日期:2014-05-16  浏览次数:20614 次

linux下gcc怎么编译动态库以及怎么像自带库一样使用自制的库
我使用的是ubuntu系统,以下是我的信息:
Linux localhost 3.2.0-39-generic-pae #62-Ubuntu SMP Wed Feb 27 22:25:11 UTC 2013 i686 i686 i386 GNU/Linux
我想自己写了个函数,以后就想使用标准库中函数一样使用它(像使用read(),write()一样),
我自己试验了一个,写了一个add函数

文件add.c:
int add(int a, int b)
{
  return a + b;
}



然后对add.c文件进行编译
gcc -fPIC -shared -o libadd.so add.c

测试程序test.c
#inclucde <stdio.h>
int main()
{
  int a = add(1, 2);
  return 0;
}


然后编译 
gcc -o test test.c -L. -ladd

运行./tesst 通过

如果我直接编译 gcc test.c ,出错 
/tmp/ccdwGdzl.o: In function `main':
test.c:(.text+0x19): undefined reference to `add'
collect2: ld returned 1 exit status

我想问的是:
1.要怎么才能在以后的函数中直接调用add(a, b),编译时直接 gcc test.c,而不用指定什么链接的。
2.还有与add对应的头文件怎么写
gcc linux C

------解决方案--------------------
需要一个add.h

add函数在add.h当中声明。
int add(int a, int b);

test.c当中
#include "add.h"

编译test的命令不变。
------解决方案--------------------
我感觉还得将编译好的库文件放到系统库文件的目录下吧,没亲自试.
------解决方案--------------------
声明一下外部函数
extern int add(int a, int b);
------解决方案--------------------
我感觉你怎么弄,也不能满足你的要求,包括把你的库放到/usr/lib下面。
在vc里面可以做到。