C语言 使用 gcc 编译基本 x86 代码时出现链接错误



我正在尝试编写非常基本的x86代码并在C程序中调用它。我正在运行OSX 10.8.2。这是我的代码:

开始.c:

#include <stdio.h>
void _main();  // inform the compiler that Main is an external function
int main(int argc, char **argv) {
    _main();
    return 0;
}

代码.s

.text
.globl _main
_main:
    ret

我运行以下命令来尝试编译:

gcc -c -o code.o code.s
gcc -c -o start.o start.c
gcc -o start start.o code.o

然后在最后一个命令之后返回此输出:

Undefined symbols for architecture x86_64:
  "__main", referenced from:
      _main in start.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status

我在编译器调用中是否缺少某些内容?我需要更新某些内容/安装其他内容吗?我只是在任何地方都找不到明确的答案,因为这是一个如此通用的输出。谢谢!

您需要在 asm _main符号中增加一个下划线:

.text
.globl __main
__main:
    ret
C

符号在编译时会得到一个下划线前缀,所以你的 C main实际上是_main的,如果你用 asm 编写一个外部 C _main实际上需要定义为 __main

最新更新