连杆c和总成
我有一个非常简单的连杆c和总成,c,gcc,assembly,ld,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; } 首先,通过键入gcc-cmain.c 然后我得到hello.o--nasm-f macho hello.asm-DDARWIN 最后,为了得到一个可执行文件,我执行了ld-o
main.c
文件:
#include <stdio.h>
int cnt;
extern void increment();
int main()
{
cnt = 0;
increment();
printf("%d\n", cnt);
return 0;
}
首先,通过键入gcc-cmain.c
然后我得到hello.o
--nasm-f macho hello.asm-DDARWIN
最后,为了得到一个可执行文件,我执行了ld-o 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
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
@因为那不起作用
gcc
不知道调用nasm
@Jester:是的,我刚刚意识到它不是用gas assembly编写的…你是在64位操作系统上吗?然后对您的main.c
执行gcc-m32
。按照@EOF的建议,您也可以在获得hello.o
后使用gcc作为:gcc main.c hello.o
(如有必要,添加-m32
)。@Jester with-m32选项I not get file是针对不支持的文件格式错误生成的。但其他错误仍然存在。这可能会起作用,请尝试在数据节中的程序集文件中定义cnt
,例如cnt dw 0
,并通过在其上方添加global cnt
使其成为全局的increment
,同时删除extern cnt
行。现在在c
源代码中,将int-cnt
更改为extern-int-cnt
,希望这能使所有内容正确链接。为什么变量名前需要下划线?@luckyemi的答案在这里
file main
main: Mach-O executable i386
./main
1