Reputation: 1509
I have a primitive understanding of how the linker does dead-code elimination of unused functions and data segments. If you use the proper compiler and linker flags it puts each function and data member into it's own section, then when the linker goes to link them it will see that, if not referenced directly, nothing links into that section and then it will not link that section into the final elf.
I'm trying to reconcile how that works with function pointers. You could, for example, have a function pointer whose value is based on user input. Probably not a safe thing to do, but how would the compiler and linker handle that?
Upvotes: 5
Views: 630
Reputation: 114481
There is no portable way to assign a function pointer without making an explicit reference to the function (for example you cannot use pointer arithmetic on function pointers).
So every function that is reachable from your program must also be named and referenced in the code and the linker will know about it. Just even storing the function pointer in an array like in:
typedef void (*Callback)();
Callback callbacks[] = { foo, bar, baz };
is enough to ensure that the functions listed will be included in the linked executable (the array content will be fixed at load time or at link time depending on the platform).
Upvotes: 4