Use label in assembly from C

Kendall Frey picture Kendall Frey · Nov 8, 2011 · Viewed 10.7k times · Source

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 and nasm to assemble these files. How can I load the label address?

Answer

ughoavgfhw picture ughoavgfhw · Nov 8, 2011

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");