Page 1 of 1
How to pass arguments to the 6502 code from C?
Posted: Mon Sep 03, 2018 11:53 pm
by milap
I am trying to compile C and 6502 code using cc65 simulator. I wish to pass value as an argument to the 6502 code? How do I do that?
My C code "main.c":
#include<stdio.h>
#define N 10
int foo(int data);
int main() {
uint8_t p = foo(N);
printf("%u\n",p);
return 0;
}
My 6502 code "foo.s":
.export _foo
LDA #the_variable_received_from_C
STA $0200
Re: How to pass arguments to the 6502 code from C?
Posted: Tue Sep 04, 2018 2:49 am
by BigEd
Welcome!
It looks like the answers can be found in the cc65 wiki:
which has an example, and explains that the callee must clean up the parameter stack.
You need to use the zeropage pointer 'sp', as explained:
The runtime zeropage locations used by the compiler are declared in the assembler include file zeropage.inc.
-
Using runtime zeropage locations in assembly language
(BTW you wrote 'cc65 simulator' but meant to write 'cc65 compiler')
Re: How to pass arguments to the 6502 code from C?
Posted: Tue Sep 04, 2018 3:35 am
by milap
Welcome!
It looks like the answers can be found in the cc65 wiki:
which has an example, and explains that the callee must clean up the parameter stack.
You need to use the zeropage pointer 'sp', as explained:
The runtime zeropage locations used by the compiler are declared in the assembler include file zeropage.inc.
-
Using runtime zeropage locations in assembly language
(BTW you wrote 'cc65 simulator' but meant to write 'cc65 compiler')
Thanks for your answer I tried implementing that snippet before too but I did not get the expected result.
My C code:
#include<stdio.h>
#include<stdint.h>
uint8_t cdecl foo(uint8_t bar);
int main() {
uint8_t p = foo(5);
printf("%u\n",p);
return 0;
}
My 6502 code:
.export _foo
.importzp sp, sreg, regsave
LDY #2
LDA (sp),Y
TAX
DEY
LDA (sp),Y
I always get the result as
255
Maybe something wrong in my C code?
Re: How to pass arguments to the 6502 code from C?
Posted: Tue Sep 04, 2018 8:11 am
by BigEd
According to my reading of those two wiki pages, there are a few things I think need to be done differently:
- you're reading bytes 2 and 1 from the stack, as if it were the first of two parameters and a 16 bit value, but your parameter is on byte 0 of the stack, because it's the first parameter and is an 8 bit value.
- you are not adjusting sp to remove your parameter before returning - that's your callee cleanup responsibility.
- you need to return your desired value in A (low byte) and X (high byte) by extending it to 16 bits.