简体   繁体   English

如何从C代码调用汇编函数?

[英]How can I call assembly function from C code?

I use avr-as assembler. 我使用avr-as汇编程序。 I want to use functions defined in assembly from a C file. 我想使用在C文件中的程序集中定义的函数。 How can I use assembly code in C code? 如何在C代码中使用汇编代码?

I am looking for solutions where the assembly source is in a separate source, ie not inlined into the C source. 我正在寻找汇编源位于单独源中(即未内联到C源中)的解决方案。

Here's a simple example to get you started. 这是一个入门的简单示例。 Suppose you want to write a main loop in C and you want to call a function written in assembly to blink PB5. 假设您要用C编写一个main循环,并且要调用用汇编编写的函数来使PB5闪烁。

The C source declares and uses (but doesn't define) blinkPB5 : C源代码声明并使用(但未定义) blinkPB5

/* main.c */
#include <avr/io.h>
#include <util/delay.h>

extern void blinkPB5();

int main ()
{
    DDRB |= _BV(DDB0);

    for (;;)
    {
        blinkPB5();
        _delay_ms(500);
    }
}

The assembly source defines blinkPB5 . 程序集源定义blinkPB5 Note that .global is used to export blinkPB5 : 请注意, .global用于导出blinkPB5

;; blinkPB5.s
.global blinkPB5

.section .text

blinkPB5:       
        ldi r25, 0x01
        in  r24, 0x05
        eor r24, r25
        out 0x05, r24
        ret

.end        

The two can be compiled separately: 两者可以分别编译:

avr-gcc -c -O3 -w -mmcu=atmega328p -DF_CPU=1000000L main.c -o _build/main.c.o
avr-gcc -c -O3 -w -mmcu=atmega328p -DF_CPU=1000000L blinkPB5.s -o _build/blinkPB5.s.o

then linked together, and formatted into a .hex image: 然后链接在一起,并格式化为.hex图像:

avr-gcc -Os -Wl,--gc-sections -mmcu=atmega328p _build/main.c.o _build/blinkPB5.s.o -o _build/image.elf
avr-objcopy -Oihex -R.eeprom _build/image.elf _build/image.hex

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

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