gbdk-2020 | GameBoy Development Kit |
| download: https://git.y1.nz/archives/gbdk.tar.gz | |
| README | Files | Log | Refs | LICENSE |
gbdk-lib/examples/gb/ram_function/ram_fn.c
1 #include <gb/gb.h>
2 #include <stdint.h>
3 #include <stdio.h>
4 #include <string.h>
5
6 uint16_t counter = 0;
7
8 // inc() must be a relocatable function, be careful!
9 void inc(void) {
10 counter++;
11 }
12 // dummy function, needed to calculate inc() size, must be after it
13 void inc_end(void) {}
14
15 // calculate the distance between objects
16 #define object_distance(a, b) ((void *)&(b) - (void *)&(a))
17
18 // variables at an absolute addresses which are defined by passing parameters to compiler
19 unsigned char __at _inc_ram ram_buffer[];
20 unsigned char __at _inc_hiram hiram_buffer[];
21
22 // those are function pointer variables, we can initialize them right here
23 typedef void (*inc_t)(void);
24 inc_t inc_ram_var = (inc_t)ram_buffer;
25 inc_t inc_hiram_var = (inc_t)hiram_buffer;
26
27 // those are defined by passing parameters to the linker, they must be located at the same
28 // addresses where ram_buffer and hiram_buffer are located
29 extern void inc_ram(void);
30 extern void inc_hiram(void);
31
32 void print_counter(void) {
33 printf(" Counter is %u\n", counter);
34 }
35
36 void main(void) {
37 // copy inc() function to it's new destinations: hiram_buffer and ram_buffer
38 hiramcpy((uint8_t)&hiram_buffer, (void *)&inc, (uint8_t)object_distance(inc, inc_end));
39 memcpy(&ram_buffer, (void *)&inc, (uint16_t)object_distance(inc, inc_end));
40
41 // print initial counter state
42 puts("Program Start...");
43 print_counter();
44
45 // Call function in ROM
46 puts("Call ROM");
47 inc();
48 print_counter();
49
50 // Call function in RAM using link-time address
51 puts("Call RAM direct");
52 inc_ram();
53 print_counter();
54
55 // Call function in RAM using pointer-to-function variable
56 puts("Call RAM indirect");
57 inc_ram_var();
58 print_counter();
59
60 // Call function in HIRAM using link-time address
61 puts("Call HIRAM direct");
62 inc_hiram();
63 print_counter();
64
65 // Call function in HIRAM using pointer-to-function variable
66 puts("Call HIRAM indirect");
67 inc_hiram_var();
68 print_counter();
69
70 puts("The End...");
71 }
This webpage is intended to be an accessible preview of this repository. To get a fuller picture, clone it and use the git CLI.