If I define a function but don't call it, function will not presented in executable. But there are situation when we need to tell linker not to exclude a function. For example I have defined functions that should be called by totalview
debugger in debug time.
If I call that function from somewhere (from main function for example) the problem will be solved, it will not excluded, but is there a general rule to tell linker not to exclude a function?
You could use GCC's attribute externally_visible
to guarantee the function will exist.
It would look like this:
#include <stdio.h>
__attribute__((externally_visible))
int f(int x) {
return x+2;
}
int main() {
int x = f(2);
printf("x=%d\n", x);
return 0;
}
This question dealt with a similar problem, but it was focused on forcing the compiler to include a function, not the linker.
Still, paxdiablo's answer still applies here - you can create a global array of all the functions you want to include. The linker won't know if there's anybody using that array as a jump table, so it has to include the functions. (A really smart linker might know that this array is never accessed, but then you could go a step further and have a function access the array, although at that point it will get ugly).
Here's the code paxdiablo suggested, slightly renamed:
void *functions_to_forceinclude[] = {
&functionToForceIn,
&anotherFunction
};
This is technically a hack, but it's simple and pretty portable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With