c - 链接 c 和程序集

标签 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

首先,我通过输入 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)
  • 链接 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

关于c - 链接 c 和程序集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29927601/

相关文章:

c - 结构大小问题,要求不需要的内存?

c++ - 带有/SAFESEH 的自定义 SEH 处理程序

assembly - 为什么 cmp 指令中的参数顺序很重要?

c - 如何访问 C 结构体中的指针成员?

c - 错误 : declared as function returning an array in c (mpfr libary)

c - 用 __stdcall 替换 FAR 和 PASCAL

gcc - glib 版本不是所需的最低版本

c++ - 调试堆栈值损坏的好方法

c++ - 在 x64 上获取没有 __asm 的 SSE 版本

c - BST 二叉树删除 C 中值 = 0 的叶子的函数