Ashot
Ashot

Reputation: 10959

How to make linker not to exclude uncalled function?

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?

Upvotes: 5

Views: 1477

Answers (2)

Zan Lynx
Zan Lynx

Reputation: 54325

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

Upvotes: 3

EboMike
EboMike

Reputation: 77752

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.

Upvotes: 1

Related Questions