How to call code written in C from the assembly?

SOLVED QUESTION Must make the main character global so that the linker can find it in the object file when linking. The corrected code.

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

Wrote a C function:

#include <stdio.h> void func_in_c(char *s) { printf("%s", s); } 

wrote a call failure 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 with one executable binary:

 gcc -o main main_c.o main.o 

got:

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

Do you have any suggestions for fixing commands / code to build an executable? Yes, I read similar questions (using the NASM assembler, no solutions work).

+5
source share
1 answer

First you need to make the main label global, because otherwise the object file will not contain a character, and the linker will not recognize it.

+3
source

All Articles