设为首页 加入收藏

TOP

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

 

  另外还有一点需要注意,因为这里重写了_start函数,所以gcc为默认的main函数准备的清理动作就没用上,所以如果退出的时候直接使用return,会导致程序崩溃。所以这里要使用exit()来退出程序。具体的原因可以参见这篇文章。

  3、gcc的-e选项

  示例程序如下:

  #include

  #include

  int nomain(int i, int j, int k) {

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

  exit(0);

  }

  将上面的程序保存为m.c,编译命令如下所示:

  gcc -nostartfiles -e nomain m.c -o a.out

  继续使用objdump反汇编生成的可执行程序,结果如下:

  a.out: file format elf64-x86-64

  Disassembly of section .plt:

  0000000000400320 :

  400320: ff 35 f2 01 20 00 pushq 0x2001f2(%rip) # 600518 <_GLOBAL_OFFSET_TABLE_+0x8>

  400326: ff 25 f4 01 20 00 jmpq *0x2001f4(%rip) # 600520 <_GLOBAL_OFFSET_TABLE_+0x10>

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

  0000000000400330 :

  400330: ff 25 f2 01 20 00 jmpq *0x2001f2(%rip) # 600528 <_GLOBAL_OFFSET_TABLE_+0x18>

  400336: 68 00 00 00 00 pushq $0x0

  40033b: e9 e0 ff ff ff jmpq 400320

  0000000000400340 :

  400340: ff 25 ea 01 20 00 jmpq *0x2001ea(%rip) # 600530 <_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 :

  400350: 55 push %rbp

  400351: 48 89 e5 mov %rsp,%rbp

  400354: 48 83 ec 10 sub $0x10,%rsp

  400358: 89 7d fc mov %edi,-0x4(%rbp)

  40035b: 89 75 f8 mov %esi,-0x8(%rbp)

  40035e: 89 55 f4 mov %edx,-0xc(%rbp)

  400361: bf 75 03 40 00 mov $0x400375,%edi

  400366: e8 c5 ff ff ff callq 400330

  40036b: bf 00 00 00 00 mov $0x0,%edi

  400370: e8 cb ff ff ff callq 400340

  从上面我们可以看到指定的nomain函数位于.text段的开始位置,同样在函数结束的时候没有gcc为main函数准备的清理动作,所以在这里也只能使用exit()来退出程序,而不能使用return。

  4、nostartfiles选项

  前面已经多次使用了该选项,不过都是配合其他选项使用的,这个选项也可以单独使用,其含义为"Do not use the standard system startup files when linking"。

  示例程序如下:

  #include

  #include

  void func() {

  printf("I am func....\n");

  }

  int nomain1(int i, int j, int k) {

  func();

  printf("%s: Hello, World!\n", __func__);

  exit(0);

  }

  上面的程序保存为k.c,然后使用下面的命令编译:

  [root@CentOS_190 ~]# gcc -nostartfiles p.c

  /usr/bin/ld: warning: cannot find entry symbol _start; defaulting to 0000000000400398

  在单独使用nostartfiles选项时会报警告,生成的可执行程序可以执行,但是会产生段错误,去掉对func()函数的调用就不会产生段错误了。将生成的可执行程序反汇编,和使用前面的方法生成可执行程序的反汇编结果比较,发现除了函数名不一样外,没有其他区别,不知道为什么会产生段错误。知道的麻烦告知一声,拜谢!

      

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

评论

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