Search code examples
cgnu-assembler

how to get the address of an asm function in c


I have an asm file (I'm using gas) and a c file. My asm file contains a function, something like this

.global myfunc
.type myfunc, @function

myfunc:
   pusha
   .
   .
   .

now I want to get the address of the label myfunc from my c file, so I've wrote

extern uintptr_t _myfunc asm("myfunc");

my program links without problems, but when I execute my program the variable _myfunc doesn't contain the right address.

Edit 1

maybe it's useful to know that this piece of code is part of a bare-metal program

Edit 2

using a function prototype solved the problem

void function() asm("myfunc");

uintptr_t _myfunc = (uintptr_t)&myfunc;

Solution

  • You should be able to declare your asm function in C using the same symbol you use in the .global declaration:

    extern void myfunc(void);
    

    The symbols are resolved by the linker. As long as the object file created from your asm file exports the symbol myfunc, the object file from your C source may contain an undefined reference to it.

    Depending on the particular ABI or object file format (a.out versus ELF), you may need to use _myfunc instead of myfunc in the extern declaration.