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

时间:2022-06-26 03:11:00

I use avr-as assembler. I want to use functions defined in assembly from a C file. How can I use assembly code in C code?

我使用avr-as汇编程序。我想使用C文件中的程序集中定义的函数。如何在C代码中使用汇编代码?

I am looking for solutions where the assembly source is in a separate source, i.e. not inlined into the C source.

我正在寻找解决方案,其中汇编源在一个单独的源,即没有内联到C源。

1 个解决方案

#1


2  

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中编写一个主循环,并且您想调用汇编中写入的函数来使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. Note that .global is used to export blinkPB5:

汇编源定义了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

#1


2  

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中编写一个主循环,并且您想调用汇编中写入的函数来使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. Note that .global is used to export blinkPB5:

汇编源定义了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