Why does the library linker flag sometimes have to go at the end using GCC?

前端 未结 2 634
无人及你
无人及你 2020-11-27 17:52

I\'m writing a small C program that uses librt. I\'m quite surprised that the program won\'t compile if I place the link flag at the start instead of at the end:

At

2条回答
  •  庸人自扰
    2020-11-27 18:40

    As the linker processes each module (be it a library or a object file), it attempts to resolve each undefined symbol while potentially adding to its list of undefined symbols. When it gets to the end of the list of modules, it either has resolved all undefined symbols and is successful or it reports undefined symbols.

    In your case, when it processed librt, it had no undefined symbols. Processing proc resulted in clock_gettime being an undefined symbol. gcc will not go back and look in librt for the undefined symbols.

    For that reason, you should always have your code first, followed by your libraries, followed by platform provided libraries.

    Hope this helps.

提交回复
热议问题