5

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

Bulat M.
  • 680
  • 9
  • 25

1 Answers1

3

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.

cadaniluk
  • 15,027
  • 2
  • 39
  • 67