linux下gcc怎么编译动态库以及怎么像自带库一样使用自制的库

慧钦 2013-03-14 05:05:26
我使用的是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对应的头文件怎么写
...全文
93 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
nevil 2013-03-15
  • 打赏
  • 举报
回复
声明一下外部函数 extern int add(int a, int b);
woaishuo2011 2013-03-15
  • 打赏
  • 举报
回复
我感觉还得将编译好的库文件放到系统库文件的目录下吧,没亲自试.
youngwolf 2013-03-15
  • 打赏
  • 举报
回复
我感觉你怎么弄,也不能满足你的要求,包括把你的库放到/usr/lib下面。 在vc里面可以做到。
Linux-Torvalds 2013-03-14
  • 打赏
  • 举报
回复
需要一个add.h add函数在add.h当中声明。 int add(int a, int b); test.c当中 #include "add.h" 编译test的命令不变。

23,114

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧