When linking statically, does the linker include the whole library?

后端 未结 4 508
失恋的感觉
失恋的感觉 2020-12-16 14:48

For example, if I static link to freeglut, does the compiler include everything from freeglut or only the parts that I use? Of course, this implies that the linker (or compi

相关标签:
4条回答
  • 2020-12-16 15:17

    Linker include only symbols, which are needed.

    Probably, the question about inspecting *.lib files, answers the second part (dumpbin works for *.exe files too).

    0 讨论(0)
  • 2020-12-16 15:20

    Yes, the linker will include just the translation units that your code references.

    If you generate a map file for your executable then you can see exactly what it contains.

    0 讨论(0)
  • 2020-12-16 15:27

    I think you can write a sample lib to get the answer. In a C++ lib, 1 write a class to print all the subclass name. 2 and several class derived from it.

    In a real main program, just use one of the sub-classes.

    And then print all the name.

    Then you will find the answer, I think.

    0 讨论(0)
  • 2020-12-16 15:32

    It's partly a Quality of Implementation issue, but there is a real gotcha.

    Namely, by the standard the linker has to add in all compilation units that are referenced. But say that in the library, you have a compilation unit with nothing but a static variable whose initialization registers something with a something registry, e.g. message handling, factory, whatever, or perhaps its constructor and destructor output, respectively, "before main" and "after main". If nothing in that compilation unit is referenced, then the linker is within its rights to just skip it, remove it.

    So, to ensure that such static variables are not optimized away, with a standard-conforming toolchain it is necessary and sufficient to reference something in that compilation unit.

    Re seeing in Visual Studio what has been included, as far as I know there's no way except asking for verbose output from the linker, like, linker option /verbose:ref.

    However, with that option you get really verbose output.

    An alternative is to ask the linker for a map file, like, linker option /map:blah.

    Also this output is very verbose, though.

    0 讨论(0)
提交回复
热议问题