简体   繁体   English

如何在 C 代码中调用用 ARM 汇编编写的函数?

[英]How can I call a function written in ARM assembly within C code?

To be specific:再具体一点:

  1. The arm assembly function is written in a separated file such as .S file or .asm file. arm 汇编函数写在一个单独的文件中,例如 .S 文件或 .asm 文件。
  2. I need to call this function in main.c我需要在 main.c 中调用这个函数
  3. The ARM assembly is in ARMv8 architecture. ARM 程序集采用 ARMv8 架构。

I've written some testing code but it fails to work.我写了一些测试代码,但它无法工作。

#include <stdio.h>
extern int a_add(int a, int b);
int main(){
    int fi=5;
    int se=7;
    int result=a_add(fi, se);
    printf("result is %d", result);
    return 0;
}

And following is the assembly code.(a_add.S)以下是汇编代码。(a_add.S)

.section .text
.globl a_add
a_add:
    add x3,x1,x0
    mov x0,x3
    br x30

Does anyone know how I can fix these two files to let the a_add function work?有谁知道我如何修复这两个文件以让 a_add 函数工作? I haven't tried .asm file yet.我还没有尝试过 .asm 文件。

Any help is appreciated and please forgive if I made mistakes on expression, but I hope my question is clear.感谢任何帮助,如果我在表达上犯了错误,请原谅,但我希望我的问题很清楚。

I have fixed the code by using extern "C" and have solved the problem.我已经使用 extern "C" 修复了代码并解决了问题。 What needed is just claim the function as following in main.cpp or main.c所需要的只是在 main.cpp 或 main.c 中声明如下功能

extern "C" {int a_add(int a, int b);}

Replace the old "extern" line by this line with "C".用“C”替换旧的“extern”行。 This is helpful if the compiler is for C++ code instead of C code, basically by letting the function compiled in the way of C code, not C++ code.如果编译器用于 C++ 代码而不是 C 代码,这将很有帮助,基本上是通过让函数以 C 代码而不是 C++ 代码的方式编译。

I haven't made such test but I suppose if the compiler is C compiler, there won't be such a problem.我没有做过这样的测试,但我想如果编译器是C编译器,就不会有这样的问题。

main.c主文件

#include<stdio.h>

extern int a_add(int, int);

int main() {
  int a = 5;
  int b = 3;
  printf("%d + %d = %d \n",  a, b, a_add(a, b));
}

add.s添加.s

        .text
        .global a_add
a_add:
        add     w0, w0, w1
        ret

Compiled with gcc (9.3.0) on an AArch64 machine (a docker container with ubuntu 20.04) using:在 AArch64 机器(带有 ubuntu 20.04 的 docker 容器)上使用 gcc (9.3.0) 编译,使用:

gcc main.c add.s -o run.exe && ./run.exe

A quick way to get the skeleton ready for a desired function in a target assembly would be:让骨架为目标装配中的所需功能做好准备的一种快速方法是:

  1. Write a simple c function matching the signature of the desired function, eg, for the add function above:编写一个与所需函数签名匹配的简单 c 函数,例如,对于上面的 add 函数:
int a_add(int a, int b){
  return a + b;
}
  1. Generate assembly for such C function to begin with.为这样的 C 函数生成汇编开始。
gcc -S -O2 add.c

Note: Using higher optimisation level might produce less obvious code.注意:使用更高的优化级别可能会产生不太明显的代码。

Tip : Compiler Explorer is a good tool to know while playing around with the assembly.提示编译器资源管理器是一个很好的工具,可以在使用程序集时了解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM