有没有办法让 gcc 输出原始二进制文件? [英] Is there a way to get gcc to output raw binary?

查看:23
本文介绍了有没有办法让 gcc 输出原始二进制文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一组命令行选项可以说服 gcc 从独立的源文件生成平面二进制文件?例如,假设 foo.c 的内容是

Is there a set of command-line options that will convince gcc to produce a flat binary file from a self-contained source file? For example, suppose the contents of foo.c are

static int f(int x)
{
  int y = x*x;
  return y+2;
}

没有外部引用,没有什么可以导出到链接器.我想得到一个只有这个功能的机器指令的小文件,没有任何其他装饰.除了 32 位保护模式外,有点像 (DOS) .COM 文件.

No external references, nothing to export to the linker. I'd like to get a small file with just the machine instructions for this function, without any other decoration. Sort of like a (DOS) .COM file except 32-bit protected mode.

推荐答案

试试这个:

$ gcc -c test.c     
$ objcopy -O binary -j .text test.o binfile

您可以使用 objdump 确保它是正确的:

You can make sure it's correct with objdump:

$ objdump -d test.o 
test.o:     file format pe-i386


Disassembly of section .text:

00000000 <_f>:
   0:   55                      push   %ebp
   1:   89 e5                   mov    %esp,%ebp
   3:   83 ec 04                sub    $0x4,%esp
   6:   8b 45 08                mov    0x8(%ebp),%eax
   9:   0f af 45 08             imul   0x8(%ebp),%eax
   d:   89 45 fc                mov    %eax,-0x4(%ebp)
  10:   8b 45 fc                mov    -0x4(%ebp),%eax
  13:   83 c0 02                add    $0x2,%eax
  16:   c9                      leave  
  17:   c3                      ret  

并将其与二进制文件进行比较:

And compare it with the binary file:

$ hexdump -C binfile 
00000000  55 89 e5 83 ec 04 8b 45  08 0f af 45 08 89 45 fc  |U......E...E..E.|
00000010  8b 45 fc 83 c0 02 c9 c3                           |.E......|
00000018

这篇关于有没有办法让 gcc 输出原始二进制文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆