Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

link c and assembly

Tags:

c

gcc

assembly

ld

I have a very simple main.c file:

#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.o by typing gcc -c main.c Then I get hello.o -- nasm -f macho hello.asm -DDARWIN And, finally, to get an executable I do ld -o main main.o hello.o -arch i386 -lc and get an error:

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 do I fix this linking error?

like image 311
theluckyemil Avatar asked Nov 09 '22 14:11

theluckyemil


1 Answers

  • Specify architecture (32/64 bit with options m32 or m64)
  • link crt files, these files contain the runtime - that's the 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 arch and execute:

file main
main: Mach-O executable i386

./main
1
like image 199
Laser Avatar answered Nov 15 '22 11:11

Laser