C语言之gcc编译过程(十二)

一、C语言gcc编译过程:

.c/*源代码文件*/
.h/*C语言头文件*/
.i/*经过预处理之后的源代码文件*/
.s/*汇编代码文件*/
.o/*目标代码文件(二进制机器指令文件)*/
.a/*静态对象库文件*/
.so/*共享(动态)对象库文件*/



一个程序的编译到运行gcc file.c执行了什么?其文件类型有何变化?如下图所示,最终我们只能看到a.out这个可执行文件:

è¿éåå¾çæè¿°

 

è¿éåå¾çæè¿°

*****************************************************************************************
练习:test.c
#include <stdio.h>
int main(){
  printf("Test !\n");
  return 0;
}
*****************************************************************************************
1.预处理:把.c和.h文件生成.i文件
# gcc –E hello.c –o hello.i

注意:预处理把stdio.h中不管有关没关的内容都进了main.i文件之中。

2.汇编:把预处理.i文件生成汇编文件.s
# gcc –S hello.i –o hello.s

3.目标文件:把汇编文件.s生成目标文件.o
# gcc –c hello.s –o hello.o

4.链接: 把目标文件.o生成可执行文件(动态库 OR 静态库)
<1>.编译可执行文件
# gcc hello.o -o hello //可执行文件

or其他用法
# gcc test.c -L/path -lxxx -o test

<2>.编译动态库
# gcc -fPIC -shared file1.c -o libxxx.so

也可分成两部:
# gcc -fPIC test.c -c //这一步生成file1.o
# gcc -shared test.o -o libtest.so
注意:运行程序的时候,需要指定动态库的位置,可以环境变量来指定,export LD_LIBRARY_PATH=path,否则会提示找不到动态库的位置.

<3>.编译静态库
# ar cr libxxx.a test1.o test2.o

二、C/C++函数宏定义使用

1.相关宏定义
__LINE__ /*显示所在行,%d输出*/
__FILE__ /*当前文件名,%s输出*/
__DATE__ /*当前日期,%s输出*/
__TIME__ /*当前时间,%s输出*/
__FUNCTION__ /*所在函数名,%s输出*/

2.使用test.c
#include <stdio.h>
int main(){
  printf("%s, %s(), %d, %s, %s\n",__FILE__, __FUNCTION__, __LINE__, __DATE__, __TIME__);
  return 0;
}
0.test.h
int NTFS = 10;
int NNNN = 500

1.test.c
#include <stdio.h>
#include "test.h"
int print(){
  printf("NTFS = %d\n", NTFS);
  printf("NNNN = %d\n", NNNN);
  return 0;
}
编译so
# gcc -fPIC  -shared test.c -o libtest.so

2.调用
main.c
include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>

typedef int (*PRINT)();

int main(){
  void *handle=dlopen("./libtest.so",RTLD_LAZY);
  PRINT print=NULL;

  *(void **)(&print)=dlsym(handle,"print");
  print();
  return 0;
}

编译测试程序:
#  gcc main.c -L ./ -ltest -o main -ldl
# ./main
NTFS = 10
NNNN = 500
注意:说明test.h已经编译到libtest.so里.

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Android系统攻城狮

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值