Gcc remove dead code with function pointers

I have a primitive understanding of how the linker does the elimination of unused functions and data segments. If you are using the correct compiler and linker flags, it puts each function and data item in its own section, and then when the linker goes to their link, it sees that if not directly referenced, nothing links to that section, and then it will not link this section to the last elf.

I am trying to reconcile how this works with function pointers. For example, you might have a function pointer whose value is based on user input. Probably not a safe thing to do, but how do you deal with the compiler and linker?

+3


source to share


1 answer


There is no portable way to assign a function pointer without an explicit reference to the function (for example, you cannot use pointer arithmetic on function pointers).

Therefore, every function accessible from your program must also be named and specified in the code, and the linker will know about it. By simply storing the function pointer in an array, for example:



typedef void (*Callback)();
Callback callbacks[] = { foo, bar, baz };

      

it is enough that the listed functions are included in the associated executable (the contents of the array will be fixed at boot time or at connection time depending on the platform).

+3


source







All Articles