加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

链接c和汇编

发布时间:2020-12-16 07:11:51 所属栏目:百科 来源:网络整理
导读:我有一个非常简单的main.c文件: #include stdio.hint cnt;extern void increment();int main(){ cnt = 0; increment(); printf("%dn",cnt); return 0;} 甚至更简单的hello.asm: EXTERN cntsection .text global increment increment: inc dword [cnt]ret
我有一个非常简单的main.c文件:

#include <stdio.h>
int cnt;
extern void increment();
int main()
{
    cnt = 0;
    increment();
    printf("%dn",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位,选项m32或m64)
>链接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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读