C语言struct机制

来源:互联网 发布:统一软件过程图 编辑:程序博客网 时间:2024/05/18 14:15
test.c
  1#include<stdio.h>
 
  3 struct test
  4 {
  5        int a;
  6        char* b;
  7        int c;
  8 };     
  9 void main()
 10 { 
 11 
 12        struct test test[2]={
 13        {1,"hello,world",30}
 14        ,{2,"hello,again",20}};
 15 }
  
编译
gcc -o test.c
反汇编
objdump -d test.o

test.o:     file formatelf64-x86-64

Disassembly of section .text:

0000000000000000 <main>:
   0: 55                push  %rbp
   1: 48 89 e5           mov   %rsp,%rbp
   4: c7 45 d0 01 00 00 00movl   $0x1,-0x30(%rbp)       #test[0].a=1
   b: 48 c7 45 d8 00 00 00movq   $0x0,-0x28(%rbp)      #test[0].b=0x0 0x0为重地位地址,链接后会替换为“hello, world"的地址
  12: 00 
  13: c7 45 e0 1e 00 00 00 movl  $0x1e,-0x20(%rbp)      #test[0].c=30
  1a: c7 45 e8 02 00 00 00 movl  $0x2,-0x18(%rbp)       #下面对应与test[1]的赋值
  21: 48 c7 45 f0 00 00 00 movq  $0x0,-0x10(%rbp)
  28: 00 
  29: c7 45 f8 14 00 00 00 movl  $0x14,-0x8(%rbp)
  30: 5d                pop   %rbp
  31: c3                retq

由反汇编代码可知,struct用于告知汇编器对象类型所占内存大小,链接过程不涉及struct。如果一个源文件要使用某一struct类型(比如定义struct对象,访问struct成员),那么必须自己定义该struct或包含定义该struct的头文件。如果仅仅是定义一个struct对象指针,则只需声明struct即可(structname;)。


参考
http://huobengle.iteye.com/blog/1382039
原创粉丝点击