设为首页 加入收藏

TOP

C语言main函数生成可执行法(一)
2014-04-06 17:41:33 来源: 作者: 【 】 浏览:293
Tags:语言 main 函数 生成 执行

  1、define预处理指令

  这种方式很简单,只是简单地将main字符串用宏来代替,或者使用##拼接字符串。示例程序如下:

  #include

  #define begin main

  int begin(void)

  {

  printf("Hello, World!\n");

  return 0;

  }

  #include

  #define begin m##a##i##n

  int begin(void)

  {

  printf("Hello, World!\n");

  return 0;

  }

  严格来说,这种方式只算是一种技巧......

  2、_start函数

  _start函数是C程序的入口函数,会调用main函数。在调用main函数之前,会先执行_start函数分配必要的资源,然后再调用main函数。但是在用gcc编译程序时可以使用-nostartfiles选项来重写_start函数。示例程序如下:

  #include

  #include

  _start(void) {

  printf("Hello, World!\n");

  exit(0);

  }

  编译上面的程序的命令为:

  gcc -nostartfiles _start.c -o a.out

  反汇编生成的可执行程序,如下所示:

  a.out: file format elf64-x86-64

  Disassembly of section .plt:

  0000000000400320 :

  400320: ff 35 ea 01 20 00 pushq 0x2001ea(%rip) # 600510 <_GLOBAL_OFFSET_TABLE_+0x8>

  400326: ff 25 ec 01 20 00 jmpq *0x2001ec(%rip) # 600518 <_GLOBAL_OFFSET_TABLE_+0x10>

  40032c: 0f 1f 40 00 nopl 0x0(%rax)

  0000000000400330 :

  400330: ff 25 ea 01 20 00 jmpq *0x2001ea(%rip) # 600520 <_GLOBAL_OFFSET_TABLE_+0x18>

  400336: 68 00 00 00 00 pushq $0x0

  40033b: e9 e0 ff ff ff jmpq 400320

  0000000000400340 :

  400340: ff 25 e2 01 20 00 jmpq *0x2001e2(%rip) # 600528 <_GLOBAL_OFFSET_TABLE_+0x20>

  400346: 68 01 00 00 00 pushq $0x1

  40034b: e9 d0 ff ff ff jmpq 400320

  Disassembly of section .text:

  0000000000400350 <_start>:

  400350: 55 push %rbp

  400351: 48 89 e5 mov %rsp,%rbp

  400354: bf 68 03 40 00 mov $0x400368,%edi

  400359: e8 d2 ff ff ff callq 400330

  40035e: bf 00 00 00 00 mov $0x0,%edi

  400363: e8 d8 ff ff ff callq 400340 exit@plt

  上面的结果是完整的反汇编结果,我们可以看到_start函数中只有我们调用printf和exit函数相关的一些指令,并且.txt段中只有_start函数,没有看到main函数。如果将源代码中的_start替换为main,重新编译程序,反汇编的结果中会看到_start函数会调用到main。

   

首页 上一页 1 2 3 下一页 尾页 1/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇C语言语句及流程控制 下一篇float x 与“零值”比..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: