How do I make the linker not exclude an unclaimed function?

If I define a function but do not call it, the function will not appear in the executable. But there is a situation where we need to tell the linker not to exclude the function. For example, I have defined functions that should be called by the debugger totalview

in debug time.

If I call this function somewhere (for example, from the main function) the problem is solved, it will not be excluded, but is there a general rule to tell the linker not to exclude the function?

+3


source to share


2 answers


This question dealt with a similar problem, but it focused on forcing the compiler to include the feature, not the linker.

However, paxdiablo's answer still applies here - you can create a global array of all the features you want to include. The compiler won't know if there is anyone using this array as a jump table, so it must include functions. (Indeed, a smart linker might know that this array is never available, but then you can go ahead and access the array, although at this point it will get ugly).

Here's the code paxdiablo suggested, slightly renamed:



void *functions_to_forceinclude[] = {
    &functionToForceIn,
    &anotherFunction
};

      

It is technically hacky but simple and fairly portable.

+1


source


You can use the GCC attribute externally_visible

to ensure that the function will exist.

It will 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;
}

      

+1


source







All Articles