How to get the length of a function in bytes?

There is a way to determine the size of a function. The command is:

 nm -S <object_file_name>

This will return the sizes of each function inside the object file. Consult the manual pages in the GNU using 'man nm' to gather more information on this.


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 <stdio.h>

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.

Tags:

C