How to get the length of a function in bytes?

后端 未结 11 1115
醉酒成梦
醉酒成梦 2020-11-28 11:16

I want to know the length of C function (written by me) at runtime. Any method to get it? It seems sizeof doesn\'t work here.

11条回答
  •  甜味超标
    2020-11-28 11:50

    You can get this information from the linker if you are using a custom linker script. Add a linker section just for the given function, with linker symbols on either side:

    mysec_start = .;
    *(.mysection)
    mysec_end = .;
    

    Then you can specifically assign the function to that section. The difference between the symbols is the length of the function:

    #include 
    
    int i;
    
     __attribute__((noinline, section(".mysection"))) void test_func (void)
    {
        i++;
    }
    
    int main (void)
    {
        extern unsigned char mysec_start[];
        extern unsigned char mysec_end[];
    
        printf ("Func len: %lu\n", mysec_end - mysec_start);
        test_func ();
    
        return 0;
    }
    

    This example is for GCC, but any C toolchain should have a way to specify which section to assign a function to. I would check the results against the assembly listing to verify that it's working the way you want it to.

提交回复
热议问题