【问题标题】:how to call code written in C from assembly?如何从汇编中调用用 C 编写的代码?
【发布时间】:2017-01-19 00:16:18
【问题描述】:

已解决的问题 应该使主符号全局,以便链接器在链接时可以在目标文件中找到它。更正了代码。

在做任务时,尝试从程序集(YASM assembler)中调用简单的C函数:

写了C函数:

#include <stdio.h>

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

编写调用汇编代码:

        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

编译的程序集:

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

编译的c代码:

gcc -o main_c.o -c main_c.c

试图将两个目标文件链接成一个可执行的二进制文件:

gcc -o main main_c.o main.o

得到:

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

您对如何更正命令/代码以构建可执行文件有任何建议吗? 是的,我读过类似的问题(使用 NASM 汇编器,但没有解决方案有效)。

【问题讨论】:

  • main 标签设为全局。对于 GNU as,它是 .global main,我不知道 yasm。
  • 工作,谢谢。 @Downvoter,写一个答案,所以我可以接受。

标签: c x86-64 yasm


【解决方案1】:

您需要首先将main 标签设为全局,否则目标文件将不包含该符号,链接器将无法识别它。

【讨论】:

    猜你喜欢
    • 2012-04-21
    • 2016-06-01
    • 1970-01-01
    • 2016-09-07
    • 2017-02-18
    • 1970-01-01
    • 2011-09-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多