异想天开

What's the true meaning of light, Could you tell me why

32位与64位区别

日期:2015-12-20 15:39:31
  
最后更新日期:2016-12-04 14:27:28
操作机器: x86-64 i5 cpu ubantu 14.04
如何在64位操作系统上面生成32位程序?

利用如下两个gcc参数:
[code lang="cpp"]
-m32
-m64
-mx32
Generate code for a 32-bit or 64-bit environment. The -m32 option sets "int", "long", and pointer
types to 32 bits, and generates code that runs on any i386 system.

The -m64 option sets "int" to 32 bits and "long" and pointer types to 64 bits, and generates code
for the x86-64 architecture. For Darwin only the -m64 option also turns off the -fno-pic and
-mdynamic-no-pic options.

The -mx32 option sets "int", "long", and pointer types to 32 bits, and generates code for the
x86-64 architecture.
[/code]
[code lang="cpp"]
-march=cpu-type
Generate instructions for the machine type cpu-type. In contrast to -mtune=cpu-type, which merely
tunes the generated code for the specified cpu-type, -march=cpu-type allows GCC to generate code
that may not run at all on processors other than the one indicated. Specifying -march=cpu-type
implies -mtune=cpu-type.
[/code]
一个简短的程序
[code lang="cpp"]
//mm.c
int main()
{
return 0;
}
[/code]
生成32位obj文件
[code lang="cpp"]
gcc -fno-builtin -g -c -m32 -march=i686 -fno-stack-protector -nostdinc -I ../include mm.c -o mm.o
[/code]
针对32系统时,链接参数也需要修改:
[code lang="cpp"]
ld -melf_i686 -Ttext 0x706000 -Tdata 0x708000 -nostdlib -L ../lib ../lib/sys/libcrt0.a ./mm.o ./table.o ./put.o ./fork.o ./exec.o ./utility.o ./exit.o ./vm_area.o ../lib/common/page_alloc.o ../lib/sys/libsys.a ../lib/user/libc.a -o mm
[/code]
这样便可以生成32位的代码了,m32和march两个都需要加上,之前本身是32位系统,所以当时就没加m32,现在是64位系统了需要加上m32。但如果你需要写个hello world的测试例子,那么需要在64位系统安装32位的开发库和开发库的头文件。说了这么多废话,其实就是:
1.第一步确认内核架构
sudo dpkg --print-architecture
amd64
内核架构是amd64,但cpu其实是intel core i7。
2.第二步确认支持外部架构
sudo dpkg --print-foreign-architectures
i386
若没打开,那么搜索方法打开即可,wo也不会意思说来了,也是抄的。
3.第三步 安装multi库
apt-get install gcc-multilib g++-multilib

这次重新搭建环境,也是深有感触。记得一部美剧,女主人公喜欢玩电子和机械,她说,拿着锤子敲敲让她内心很平静。好了,完成了第一步修改。