Bulat M. Bulat M. - 1 month ago 6x
C Question

how to call code written in C from assembly?

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>

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
push rbp
mov rbp, rsp
lea rdi, [str_to_c]
call func_in_c

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


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).


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.