1

Assuming I'm working in an IDE like Visual Studio to program in C or C++. Let's say I decide to statically link to an object file. Because I'm using Visual Studio, I configure the project properties linker settings (i.e. I don't edit a make file). What happens if I don't actually use any of the linked code in my program? What will the compiled code look like? Will it be bloated?

Will the IDE check for such cases to optimize the makefile? Or could the compiler check for this? Would it depend on the compiler?

Essentially this question was motivated by me not knowing what libraries I will need to use from SFML, thus I decided to link to all the libraries as a temporary action. Would linking to object files that aren't implemented bloat my binaries? Or would they be optimized away by the IDE, compiler, etc.?

isanae
  • 3,253
  • 1
  • 22
  • 47
Izzo
  • 4,461
  • 13
  • 45
  • 82

1 Answers1

2

Most optimizers are able to find and eliminate dead code, and that includes functions that are never called. On Visual C++, this requires at least the /Gy flag ("Enable Function-Level Linking") to the compiler. Other flags should be on by default.

> type a.cpp
#include <iostream>

void not_called()
{
    std::cout << "Hello, world!\n";
}

int main()
{
}

> cl /nologo /EHsc /Gy a.cpp /link /verbose | findstr not_called
    Discarded "void __cdecl not_called(void)" (?not_called@@YAXXZ) from a.obj

The /Gy flag packages individual functions into COMDATs, which gives more information to the linker and allows it to remove unused or redundant functions. The linker flag /OPT:REF ("eliminates functions and data that are never referenced") is also required, but it's on by default.

Visual C++ will set these flags correctly by default in Release mode when you create a new project. However, if you're statically linking with a library, you have to make sure it was also compiled with /Gy.

Note that none of this applies to linking with a DLL. Since it's impossible to tell in advance what functions will be used when building it, the DLL will always contain everything that was exported.

Community
  • 1
  • 1
isanae
  • 3,253
  • 1
  • 22
  • 47