GCC生成动态库

main.c

1 #include <stdio.h>
2 void hello(void);
3 int main(int argc, char ** argv) 
4 {
5     printf("This is main function!\n");
6     hello();
7     return 0;
8 }

 

hello.c

1 #include <stdio.h>
2 void hello() 
3 {
4     printf("This is hello function!\n");
5 }

 

-----------------------------------------------------------------------------------------------------------------------------------------

1:gcc -shared -fPIC -o libmyhello.so hello.c

把hello.c生成动态库。

-shared表示共享,用作动态库。

-fPIC position independent code表示位置无关代码,用于动态加载。

 

2:gcc -o myhello main.c -L. -lmyhello

-l'xxxx' 表示提取libxxxx.so库文件。如实例则表示libmyhello.so。

-L'path' 表示库文件的位置在path目录下。如实例则表示在当前目录 . 。

 

3:sudo cp libmyhello.so /usr/lib/

把动态库复制到linux默认库文件/usr/lib/下。

若想在任意库目录下生产可执行文件,去掉步骤2,用gcc -o myhello main.c ./libmyhello.so取代即可。

每次运行myhello 需要保证"./libmyhello.so"的存在,不推荐使用。

 

4:./myhello 提示:

This is main function!
This is hello function!

表示运行成功!

 

posted @ 2016-06-13 01:06  Kevin_Hwang  阅读(253)  评论(0编辑  收藏  举报