Keil Logo

C51: CALLING ASSEMBLY ROUTINES FROM C


Information in this article applies to:

  • C51 All Versions

QUESTION

In the C51 compiler manual, there is example of an assembly module calling a C function. Is there any example of a C program calling an assembly routine?

ANSWER

There are no examples in the book, but it is easy to create your own. The asm routine must know how parameters are passed, values returned, and the naming conventions of segments. The steps you must follow to create an example are outlined below:

  1. Write a simple function in C that passes parameters and returns values the way you want your assembly routine to.
  2. Use the SRC directive (#PRAGMA SRC at the top of the file) so that the C compiler generates a .SRC file instead of a .OBJ file.
  3. Compile the C file. Since the SRC directive was specified, the .SRC file is generated. The .SRC file contains the assembly code generated for the C code you wrote.
  4. Rename the .SRC file to a .A51 file.
  5. Edit the .A51 file and insert the assembly code you want to execute into the body of the assembly function shell included in the .A51 file.

For example, the following code

#pragma SRC
unsigned char my_assembly_func (
  unsigned int argument)
{
return (argument + 1);   // Insert dummy lines to access all args and retvals
}

when compiled generates the following assembly SRC file.

NAME    TESTCODE

?PR?_my_assembly_func?TESTCODE                SEGMENT CODE
        PUBLIC  _my_assembly_func
; #pragma SRC
; unsigned char my_assembly_func (

        RSEG  ?PR?_my_assembly_func?TESTCODE
        USING   0
_my_assembly_func:
;---- Variable 'argument?040' assigned to Register 'R6/R7' ----
                        ; SOURCE LINE # 2
;   unsigned int argument)
; {
                        ; SOURCE LINE # 4
; return (argument + 1);   // Insert dummy lines to access all args and retvals
                        ; SOURCE LINE # 5
        MOV     A,R7
        INC     A
        MOV     R7,A
; }
                        ; SOURCE LINE # 6
?C0001:
        RET
; END OF _my_assembly_func

        END

MORE INFORMATION

SEE ALSO

ATTACHED FILES

Request the files attached to this knowledgebase article.

FORUM THREADS

The following Discussion Forum threads may provide information related to this topic.

Last Reviewed: Monday, November 26, 2012


Did this article provide the answer you needed?
 
Yes
No
Not Sure
 
  Arm logo
Important information

This site uses cookies to store information on your computer. By continuing to use our site, you consent to our cookies.

Change Settings

Privacy Policy Update

Arm’s Privacy Policy has been updated. By continuing to use our site, you consent to Arm’s Privacy Policy. Please review our Privacy Policy to learn more about our collection, use and transfers
of your data.