Is C++ linkage smart enough to avoid linkage of unused libs?

前端 未结 3 1109
囚心锁ツ
囚心锁ツ 2021-02-11 13:06

I\'m far from fully understanding how the C++ linker works and I have a specific question about it.

Say I have the following:

Utils.h

         


        
3条回答
  •  不知归路
    2021-02-11 13:41

    Think of each function as a node in a graph.
    Each node is associated with a piece of binary code - the compiled binary of the node's function.
    There is a link (directed edge) between 2 nodes if one node (function) depends on (calls) another.

    A static library is primarily a list of such nodes (+ an index).

    The program starting-node is the main() function.
    The linker traverses the graph from main() and links into the executable all the nodes that are reachable from main(). That's why it is called a linker (the linking maps the function call addresses within the executable).

    Unused functions, do not have links from nodes in the graph emanating from main().
    Thus, such disconnected nodes are not reachable and are not included in the final executable.

    The executable (as opposed to the static library) is primarily a list of all nodes reachable from main() (+ an index and startup code among other things).

提交回复
热议问题