什么是gcc&该序列的重要性? [英] What is the proper sequence of options for gcc & the importance of that sequence?

查看:136
本文介绍了什么是gcc&该序列的重要性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用这个命令来编译我的程序:
$ b $ p code>



它给未定义引用< function_name> 错误。



经过大量的试验和错误以修复错误,最后我(错误地)将选项重新排列为 gcc ,如下所示:



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



和它的工作。



我读了,我得到了它为什么发生的原因。



这里我想要要知道,是否有用于 gcc 的选项序列的规则?

PS:我知道有无限选项可用于 gcc ,我想要根据选项类别了解序列。

解决方案

列表库最后。



在编译之后,GCC将文件传递给链接器进行链接(除非要执行链接,就像请求编译时发生的那样 - 仅用 -c 开关)。它将文件按照您在命令行中列出它们的顺序(或其相应的输入)传递给链接器。



您列出了 -lpthread (这意味着pthread库,名为 libpthread.a 或类似的东西),接着是 multi_thread_server.c multi_thread_server.o 的目标文件),所以链接器首先接收库,然后接收目标文件。



当链接器处理一个库文件时,它仅从中提取提供符号定义的模块,以满足之前对该符号的引用。第一个文件中没有前面的引用,当链接器处理 multi_thread_server.o 时,它会看到引用,但是太晚了;链接器不会回到如果您首先列出 multi_thread_server.c ,链接器将会看到 multi_thread_server。 Ø

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&amp;该序列的重要性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆