cfunctionembeddedmemory-addresssdcc

How can I declare a function by memory address with SDCC


(Non-native speaker here, I apologize for the vague title)

I am using the compiler suite sdcc (3.7.0) to compile C code for the TI-82 STATS calculator. Its processor is a Z80. The OS provides several functions to interact with the device, for example ClrLcdScreen() at memory address 0x4755, which takes no arguments and returns nothing.

To "declare" and call that function in assembly, I can do the following:

ClrLcdScreen    equ     0x4755  ; Assembly equivalent of '#define ClrLcdScreen 0x4755'

        call    ClrLcdScreen    ; Call the function at memory address 0x4755

Now I am not sure how I can tell SDCC that there is a function at memory address 0x4755 that I want to call. How can I write just the declaration and have SDCC know where the definition can be found at runtime?

This is how I could imagine a solution to look like (Following code is not real, it is just made-up to demonstrate what I need):

__at__ 0x4755 void ClrLcdScreen(); // Function declaration

int main() {
    ClrLcdScreen();
}

I have tried calling the function using inline assembly:

#define ClrLcdFull() __asm__("call 0x4755")

int main() {
    ClrLcdFull();
}

That works, but is not what I want. With that code, I am managing the calling myself and SDCC does not know at all that I am calling a function.


Solution

  • You can use function pointers. There are three things you need to do

    For example:

    typedef void (*funcptr)(void);
    
    int main(void)
    {
        static const funcptr ClrLcdScreen = (funcptr)0x4755;
    
        ClrLcdScreen();
    }
    

    Here's an alternative that doesn't involve declaring a pointer variable. It just casts the address to a function pointer, and calls it.

    typedef void (*funcptr)(void);
    #define ClrLcdScreen ((funcptr)0x4755)
    
    int main(void)
    {
        ClrLcdScreen();
    }