问题描述
我使用这个命令来编译我的程序:
$ b $ p code>
它给 Ø$ C首先,它会看到它没有满意的引用。然后,当链接器处理库时,它将找到这些引用的定义,并从库中提取这些模块。
I used this command for compiling my program:
gcc -g -Wall -Werror -lpthread multi_thread_server.c -o multi_thread_socket_v4
It gave undefined reference to <function_name> error.
After of lot of trial and error to fix the error, finally I (by mistake) rearranged the options to gcc as:
gcc multi_thread_server.c -lpthread -Wall -Werror -o multi_thread_server -g
and it worked.
I read this question at SO, I got the reason as why it happened.
Here I want to know that, is there any rule for the sequence of options used for gcc?
P.S.: I know there are infinite options available for gcc, I want to know the sequence according to the category of options.
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.
这篇关于什么是gcc&该序列的重要性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!