为什么库链接器标志,有时不得不去在使用GCC结束了吗? [英] Why does the library linker flag sometimes have to go at the end using GCC?

查看:120
本文介绍了为什么库链接器标志,有时不得不去在使用GCC结束了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写一个使用librt一个小的C程序。我很惊讶,如果我把链接标志在开始,而不是在最后的程序将不能编译:

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:

目前,编译我做方案:

的gcc -o PROG prog.c中-lrt -std = gnu99

如果我是做到以下几点,它将无法找到librt的功能:

If I were to do the following, it will fail to find the functions in librt:

的gcc -std = gnu99 -lrt -o PROG prog.c中

然而,这个作品与其他图书馆。我发现这个问题试图使用一个简单的Makefile的时候。使实际编译prog.c中不顺心第一个(使用-c标志),然后做了链接。

Yet, this works with other libraries. I found the issue when attempting to use a simple Makefile. make actually compiled prog.c without liking first (using -c flag) and then did the linking.

这是Makefile文件:

This is the Makefile:

CC = gcc

CFLAGS = -std=gnu99

LIBS= -lrt

LDFLAGS := -lrt


prog: prog.o

        $(CC) -o prog prog.c -lrt -std=gnu99

输出我会得到时输入make将是:

The output I would get when typing make would be:

gcc -std=gnu99   -c -o prog.o prog.c
gcc -lrt  prog.o   -o prog
prog.o: In function `main':
prog.c:(.text+0xe6): undefined reference to `clock_gettime'
prog.c:(.text+0x2fc): undefined reference to `clock_gettime'
collect2: ld returned 1 exit status
make: *** [buff] Error 1

我现在已经制作了放链接gcc的行末一个Makefile,但我很困惑,为什么它,如果连接标志是在开始不能正常工作。

I have now crafted a Makefile that puts the linking at the end of the gcc line, however I'm puzzled why it doesn't work if the linking flag is at the start.

我想AP preciate如果有人可以给我讲解一下。谢谢你。

I would appreciate if anybody can explain this to me. Thanks.

推荐答案

作为连接过程的每个模块(可以是库或目标文件),它试图解决每个未定义的符号,同时可能增加其未定义符号列表。当它到达模块列表的,它要么已经解决了所有未定义的符号,是成功或报告未定义的符号。

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 of the list of modules, it either has resolved all undefined symbols and is successful or it reports undefined symbols.

在你的情况,当它处理librt,它没有未定义的符号。处理PROC导致clock_gettime作为一个未定义的符号。 GCC不会回去看看在librt为未定义的符号。

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.

由于这个原因,你应该始终有你的code第一,其次是你的图书馆,其次是平台提供的库。

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

希望这有助于。

这篇关于为什么库链接器标志,有时不得不去在使用GCC结束了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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