Andes Workshop

It is currently Mon Aug 26, 2019 11:59 am

All times are UTC + 8 hours [ DST ]




Post new topic Reply to topic  [ 1 post ] 
Author Message
 Post subject: Mix C code and assembly code
PostPosted: Wed Oct 30, 2013 5:50 pm 
Offline
User avatar

Joined: Fri Mar 04, 2011 9:36 pm
Posts: 500
First, you could read Chapter 8 “Application Binary Interface (ABI)” in programming guide to get related information.

A C source code can be compiled to an assembly by gcc.
For example, there is a simple C code “simple.c”.
In cygwin console, I use gcc command:
$ nds32le-elf-gcc -O2 -S simple.c
Then it generate a simple.s file.
You can use gcc to view the assembly code.
(see attached example2.zip)

a. Assembly call an C function (see attached example2.zip)

Arguments will be passed in general-purpose registers (r0-r5).
For 4-byte primitive type, the return value is returned in r0.

In C code, we write:
int a=2,b=3,c=4, sum,number;
sum=simple(a,b,c);
number=sum+1;

In Assembly, we write:
movi $r2, 4 ! Third argument:c
movi $r1, 3 ! Second argument: b
movi $r0, 2 ! First argument: a
bal simple ! bal is equal to jal, call function simple
addi $r1, $r0, 1 ! return value sum is put on $r0


b. C call a assembly function (see attached example3.zip)
In C code, we write:
int simple(int x, int y, int z)
{
int result;
result=x+y+z;
return result;
}

In Assembly, we write:
simple:
add $r0, $r1, $r0
add $r0, $r0, $r2
ret

These three arguments are passing in $r0, $1, $r2.
Return value is passing in $r0.


Download example codes:
Attachment:
example2.zip [24.44 KiB]
Downloaded 257 times

Attachment:
example3.zip [33.52 KiB]
Downloaded 269 times


Note:
The following files (main.c and simple.c) in these example are excluded from build.
Attachment:
5.gif
5.gif [ 5.67 KiB | Viewed 3407 times ]


These two files (main.c and simple.c) are just for reference.

Here are the method to exclude some files:
viewtopic.php?f=23&t=746&p=877


Top
 Profile Send private message E-mail  
 
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 1 post ] 

All times are UTC + 8 hours [ DST ]


Who is online

Users browsing this forum: No registered users and 1 guest


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Search for:
Jump to:  
Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group