Use label in assembly from C

前端 未结 2 1407
星月不相逢
星月不相逢 2020-12-31 06:13

I simply need a way to load the address of a label e.g. MyLabel: in e.g. \'src.asm\' into a variable in e.g. \'src.c\'. (These files will be linked together) I am using gcc

相关标签:
2条回答
  • 2020-12-31 06:32

    There are two steps to this. First, you must export the label as global from the assembly file using the global directive.

    global MyLabel
    
    MyLabel: dd 1234    ; data or code, in whatever section.  It doesn't matter.
    

    Next, you must declare the label as external in C. You can do this either in the code using it, or in a header.

    // It doesn't matter, and can be plain void,
    // but prefer giving it a C type that matches what you put there with asm
    extern void MyLabel(void);            // The label is code, even if not actually a function
    extern const uint32_t MyLabel[];      // The label is data
    // *not*  extern long *MyLabel, unless the memory at MyLabel *holds* a pointer.
    

    Finally, you get the address of the label in C the same way you get the address of any variable.

    doSomethingWith( &MyLabel );
    

    Note that some compilers add an underscore to the beginning of C variable and function names. For example, GCC does this on Mac OS X, but not Linux. I don't know about other platforms/compilers. To be on the safe side, you can add an asm statement to the variable declaration to tell GCC what the assembly name for the variable is.

    extern uint8_t MyLabel asm("MyLabel");
    
    0 讨论(0)
  • 2020-12-31 06:44

    You might consider an assembler "getter" routine.

    Also, you might be able to simply fake the label to look like a routine to the C binder so that you could take the address of the "procedure".

    0 讨论(0)
提交回复
热议问题