5

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?

Ashot
  • 10,807
  • 14
  • 66
  • 117
  • I suppose you're asking for GCC/ld, but you should mention it in the question. – Quentin Jun 05 '15 at 13:42
  • 1
    This is not a duplicate, as this question concerns removal by the linker, not the compiler. – Chris Stratton Jun 05 '15 at 13:55
  • Sounds like you need a linker script. There you can define in more detail what the linker shall include in the result. – harper Jun 05 '15 at 14:15
  • Sounds like you or your distribution has set the default GCC flags to remove unused code or compile with LTO. Normally GCC does not tell the linker to remove unused functions. To turn that on you usually need to use -ffunction-sections and the linker option --gc-sections – Zan Lynx Jun 05 '15 at 15:54

2 Answers2

3

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;
}
Zan Lynx
  • 53,022
  • 10
  • 79
  • 131
1

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.

Community
  • 1
  • 1
EboMike
  • 76,846
  • 14
  • 164
  • 167