What is the proper sequence of options for gcc & the importance of that sequence?

后端 未结 1 1247
夕颜
夕颜 2020-12-12 07:24

I used this command for compiling my program:

gcc -g -Wall -Werror -lpthread multi_thread_server.c -o multi_thread_socket_v4

It gave undef

相关标签:
1条回答
  • 2020-12-12 08:13

    List libraries last.

    After compiling, GCC passes files to the linker for linking (unless linking is not to be performed, as happens when you request compilation-only with the -c switch). It passes the files to the linker in the order you list them (or their corresponding inputs) on the command line.

    You listed -lpthread (which means the pthread library, named libpthread.a or something similar) followed by multi_thread_server.c (which gets compiled to an object file named multi_thread_server.o. So the linker receives the library first, then the object file.

    When the linker processes a library file, it extracts from it only the modules that supply a definition of a symbol that is needed to satisfy earlier references to the symbol. Since the library is the first file, there are no earlier references. When the linker processes multi_thread_server.o, it sees the references, but it is too late; the linker does not go back to the library.

    If you list multi_thread_server.c first, the linker will see multi_thread_server.o first, and it will see that it has unsatisfied referencs. Then, when the linker processes the library, it will find the definitions for those references and will extract those modules from the library.

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