Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to call code written in C from assembly?

Tags:

c

x86-64

yasm

SOLVED QUESTION Should made main symbol global, so that linker could find it in object file when linking. Corrected code.

When doing task, tried to call simple C function from the assembly(YASM assembler):

Wrote C function:

#include <stdio.h>

void
func_in_c(char *s)
{
        printf("%s", s);
}

wrote calling assembly code:

        segment .data
str_t_c db "Wow", 0

        segment .text
        global  main ; That is the solution - let linker find global symbol
        extern printf
        extern func_in_c
main:
        push rbp
        mov rbp, rsp
        lea rdi, [str_to_c]
        call func_in_c
        leave
        ret

compiled assembly:

yasm -f elf64 -m amd64 -g dwarf2 main.asm

compiled c code:

gcc -o main_c.o -c main_c.c

tried to link both object files into single executable binary file:

gcc -o main main_c.o main.o

got:

...
In function _start:
(.text+0x20): undefined reference to main
...

Do you have any suggestions how to correct commands/code to build executable? Yes, I read similar questions(using NASM assembler, no solutions work, though).

like image 866
Bulat M. Avatar asked Oct 19 '22 02:10

Bulat M.


1 Answers

You need to make the main label global first, since otherwise, the object file will not contain the symbol and the linker won't recognize it.

like image 173
cadaniluk Avatar answered Oct 21 '22 06:10

cadaniluk