关于编译器和链接器的一个实验

   首先做个试验:

test.c:

int a;
int b=34;
int add(int,int);
int main()
{
int c;
int d=26;
c=add(b,d);
return 0;
}

add.c:

int m;
int n=65;
int add(int x,int y)
{
int j;
int k=43;
j=x+y;
j=j+n;
return j;
}

利用gcc将test.c转化为汇编代码test.s:

gcc -S test.c -o test.s

test.s:

.file  "test.c"
.comm _a, 4, 2
.globl  _b
.data
.align 4
_b:
.long 34
.def ___main; .scl 2; .type 32; .endef
.text
.globl  _main
.def _main; .scl 2; .type 32; .endef
_main:
LFB0:
.cfi_startproc
pushl %ebp
.cfi_def_cfa_offset 8
.cfi_offset 5, -8
movl %esp, %ebp
.cfi_def_cfa_register 5
andl $-16, %esp
subl $32, %esp
call ___main
movl $26, 28(%esp)
movl _b, %eax
movl 28(%esp), %edx
movl %edx, 4(%esp)
movl %eax, (%esp)
call _add
movl %eax, 24(%esp)
movl $0, %eax
leave
.cfi_restore 5
.cfi_def_cfa 4, 4
ret
.cfi_endproc
LFE0:
.def _add; .scl 2; .type 32; .endef

    发现test.s中并没有add函数的信息,进一步将test.s汇编成test.o,再将之与add.c链接,成功。

    那么,将test.c中的声明出去可不可以呢?

    出去add的声明,转化为汇编代码发现与有add声明时的一样,然后链接add.c也成功了。

    那么,能不能在test.c中直接引用add.c中的变量名呢?

    将test.c改写为:

    test.c:

int a;
int b=34;
int add(int,int);
int main()
{
int c;
a=m;
int d=26;
c=add(b,d);
return 0;
}

    再处理为汇编代码时会出现未声明变量错误。

 

http://blog.csdn.net/tobacco5648/article/details/7538456

posted @ 2016-12-08 00:04  findumars  Views(335)  Comments(0Edit  收藏  举报