link c 和汇编

link c and assembly

我有一个非常简单的 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

首先我输入 gcc -c main.c 得到 main.o 然后我得到 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

如何修复此链接错误?

  • 指定架构(32/64 位,选项 m32m64
  • link 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

检查arch并执行:

file main
main: Mach-O executable i386

./main
1