简体   繁体   English

在Linux 64位上组合C和汇编(32位代码)

[英]Combining C and Assembly(32 bit code) on Linux 64 bit

I have a 64 bit Ubuntu Operating System and I have been learning 32 bit Assembly. 我有一个64位的Ubuntu操作系统,我一直在学习32位汇编。 I am trying to compile these two files: 我正在尝试编译这两个文件:

square.s: square.s:

#square.s

.section .text
.globl sqr
.type sqr, @function
sqr:
    pushl %ebp
    movl %esp, %ebp
    movl 8(%ebp), %eax
    imull %eax, %eax
    popl %ebp
    ret

main.c : main.c:

//main.c
#include <stdio.h>
extern long sqr(long);
int main(int argc, char* argv[])
{
    long squared = sqr(10);
    printf("%lu\n", squared);
    return 0;
}

On my 32bit Virtual Machine I compiled them with this command 在我的32位虚拟机上,我使用此命令编译它们

  gcc main.c square.s -o test

and it worked. 它起作用了。 The problem I am having is that I would like to compile these files on my 64bit machine. 我遇到的问题是我想在我的64位机器上编译这些文件。 I have tried several ways of compiling these files but none have worked. 我已经尝试了几种编译这些文件的方法,但没有一种方法可行。 Can anyone point me in the right direction? 谁能指出我正确的方向? Is there an option to do this? 有没有选择这样做? I have tried -m32 but that didn't work. 我试过-m32但是没有用。

When I do this: 当我这样做:

  gcc -m32 -o test main.c square.s

I get this: 我明白了:

  In file included from /usr/include/stdio.h:28:0,
             from main.c:1:
/usr/include/features.h:323:26: fatal error: bits/predefs.h: No such file or directory
compilation terminated.

Compiling / Linking 32-bit program on 64 bit ubuntu need gcc-multilib, try: 在64位ubuntu上编译/链接32位程序需要gcc-multilib,尝试:

sudo apt-get install gcc-multilib libc6-i386 lib6-dev-i386

However, this may have other problem when you try to link other libraries. 但是,当您尝试链接其他库时,这可能还有其他问题。

You would have better luck using a 32-bit chroot environment (ie running a 32-bit root on your 64-bit ubuntu). 使用32位chroot环境 (即在64位ubuntu上运行32位root)会更好。

It seems like your problem is related to 32-bit compilation in general, regardless of the assembly code. 看起来您的问题通常与32位编译有关,无论汇编代码如何。 Something is probably misconfigured. 有些东西可能是配置错误的。

Also, did you consider using inline assembly instead of a .s file? 另外,您是否考虑使用内联汇编而不是.s文件? It's much easier to integrate C and assembly this way, and you don't have to worry about calling convention details. 以这种方式集成C和汇编要容易得多,而且您不必担心调用约定细节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM