简体   繁体   English

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

[英]Linking error when compiling basic x86 code with gcc

I am attempting to write very basic x86 code and call it in a C program. 我试图编写非常基本的x86代码并在C程序中调用它。 I'm running OSX 10.8.2. 我正在运行OSX 10.8.2。 Here is the code I have: 这是我的代码:

start.c: start.c:

#include <stdio.h>

void _main();  // inform the compiler that Main is an external function

int main(int argc, char **argv) {
    _main();
    return 0;
}

code.s code.s

.text

.globl _main
_main:
    ret

I run the following commands to attempt compilation: 我运行以下命令尝试编译:

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

Which then returns this output after the final command: 然后在最终命令后返回以下输出:

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

Am I missing something in my compiler calls? 我在编译器调用中缺少什么吗? Do I need to update something/install something different? 我需要更新某些东西/安装其他东西吗? I just can't find a definitive answer anywhere since this is such a general output. 我只是在任何地方都找不到明确的答案,因为这是一个如此普遍的输出。 Thanks! 谢谢!

You need an extra underscore in your asm _main symbol: 您需要在asm _main符号中加一个下划线:

.text

.globl __main
__main:
    ret

C symbols get an underscore prefix when compiled, so your C main is actually _main and an extern C _main actually needs to be defined as __main if you write it in asm. C符号在编译时会获得下划线前缀,因此,如果您使用asm编写,则C main实际上是_main而extern C _main实际上需要定义为__main

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

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