Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 691
Ashot Avatar asked Sep 27 '22 17:09

Ashot


2 Answers

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;
}
like image 95
Zan Lynx Avatar answered Sep 30 '22 09:09

Zan Lynx


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.

like image 32
EboMike Avatar answered Sep 30 '22 09:09

EboMike