Mehrdad Mehrdad - 1 year ago 78
C Question

How to prevent the Visual C++ linker from including every function whose address is taken?

The question is pretty simple. Let's say I compile & link this code:

static char const *foo() { static char const *baz = "0123456789ABCDEF"; return baz; }
static char const *(*bar)() = foo;
int main() { return 0; }

The Visual C++ compiler or linker automatically seems to mark the string
as used, and includes it, even though it is clearly never used (despite the fact that
's address is taken).

Is there any way to make the compiler or linker avoid including code like this that isn't actually used?

Answer Source

Separating foo() and bar() to a different obj file (i.e., a different cpp) is a good start - but not enough. Turns out that when linking the executable the linker pulls in every obj file built with the exe anyway.

The second part of the solution would be to extract the cpp with foo() and bar() into a static library, and have the executable with main() link against it.

AFAICT the exact VC linking apparatus isn't officially documented, but surveyed by Raymond here. Also, this will not work if you check 'Use Library dependency inputs'

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download