Link c and assembly

I have a very simple file main.c:

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

And even simpler hello.asm:

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

First I get main.oby typing gcc -c main.c Then I get hello.o- nasm -f macho hello.asm -DDARWIN And finally, to get the executable, I do ld -o main main.o hello.o -arch i386 -lcand get the error message:

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

How to fix this binding error?

+4
source share
1 answer
  • Specify architecture (32/64 bit with m32or parameters m64)
  • link crt, these files contain runtime - code that calls your main function

Modify your asm file:

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

So, the final command lines should be:

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

Check the arch and do:

file main
main: Mach-O executable i386

./main
1
+1

All Articles