链接c和汇编

时间:2015-04-28 18:53:20

标签: c gcc assembly ld

我有一个非常简单的main.c文件:

#include <stdio.h>
int cnt;
extern void increment();
int main()
{
    cnt = 0;
    increment();
    printf("%d\n", cnt);
    return 0;
}

甚至更简单hello.asm

EXTERN cnt
section .text 
global increment 
increment:
  inc dword [cnt]
ret

首先我输入main.o获得gcc -c main.c 然后我得到hello.o - nasm -f macho hello.asm -DDARWIN 最后,为了获得可执行文件,我执行ld -o main main.o hello.o -arch i386 -lc并收到错误:

ld: warning: -macosx_version_min not specified, assuming 10.10
ld: warning: 
ignoring file main.o, file was built for unsupported file format  (   0xCF 0xFA 0xED 0xFE 0x07 0x00 0x00 0x01 0x03 0x00 0x00 0x00 0x01 0x00 0x00 0x00 ) which is not the architecture being linked (i386): main.o
Undefined symbols for architecture i386:
  "_main", referenced from:
 implicit entry/start for main executable
"cnt", referenced from:
  increment in hello.o
ld: symbol(s) not found for architecture i386

如何修复此链接错误?

1 个答案:

答案 0 :(得分:1)

  • 指定体系结构(带选项m32m64的32/64位)
  • 链接crt个文件,这些文件包含运行时 - 这是调用主函数的代码

修改您的asm文件:

EXTERN _cnt
section .text
global _increment
_increment:
  inc dword [_cnt]
ret

所以最后的命令行应该是:

gcc -c -m32 main.c
nasm -f macho hello.asm -DDARWIN
ld hello.o main.o /usr/lib/crt1.o  -lc -o main

检查拱门并执行:

file main
main: Mach-O executable i386

./main
1