How to pass arguments to the 6502 code from C?

Building your first 6502-based project? We'll help you get started here.
Post Reply
milap
Posts: 2
Joined: 03 Sep 2018
Location: Chicago, IL

How to pass arguments to the 6502 code from C?

Post 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
User avatar
BigEd
Posts: 11464
Joined: 11 Dec 2008
Location: England
Contact:

Re: How to pass arguments to the 6502 code from C?

Post 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:
Quote:
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')
milap
Posts: 2
Joined: 03 Sep 2018
Location: Chicago, IL

Re: How to pass arguments to the 6502 code from C?

Post by milap »

BigEd wrote:
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:
Quote:
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?
User avatar
BigEd
Posts: 11464
Joined: 11 Dec 2008
Location: England
Contact:

Re: How to pass arguments to the 6502 code from C?

Post 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.
Post Reply