gcc:为什么需要-lm标志来链接数学库? [英] gcc: why the -lm flag is needed to link the math library?

查看:192
本文介绍了gcc:为什么需要-lm标志来链接数学库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚发现gcc需要 -lm 标志来编译引用数学库函数的程序。我想知道为什么在编译包含其他库(如时间库)的程序时不需要显式链接标志。如果我编写一个程序调用 time()函数,即使没有链接选项,也可以毫无问题地进行编译。但是,如果没有 -lm 标志,涉及数学库的程序将无法正常工作。

任何人都可以解释这种行为背后的原因吗?感谢您的时间。

解决方案

因为没有人愿意修复的荒谬历史实践。将C和POSIX所需的所有功能合并到一个库文件中,不仅可以避免这个问题得到反复询问,而且在动态链接时也可以节省大量时间和内存,因为每个 .so 文件链接需要文件系统操作来查找和找到它,以及几个页面的静态变量,重定位等。

其中所有函数都在一个库中,并且 -lm -lpthread -lrt 等选项全部为空操作(或链接到空的 .a 文件)完全符合POSIX标准,当然更可取。



注意:我在谈论POSIX,因为C本身并没有指定如何调用编译器。因此,您可以将 gcc -std = c99 -lm 视为特定于实现的方式,因为必须针对符合性行为调用编译器。


I just discovered that the -lm flag is needed by gcc in order to compile a program that refers a function from the math library. I'm wondering why an explicit linking flag isn't needed when compiling programs containing other libraries such as the time library. If I write a program where the time() function is called, it would compile with no problems even with no linking options. But a program with the math library involved just won't work without the -lm flag.

Can anyone please explain the reason behind this behaviour? Thanks for your time.

解决方案

Because of ridiculous historical practice that nobody is willing to fix. Consolidating all of the functions required by C and POSIX into a single library file would not only avoid this question getting asked over and over, but would also save a significant amount of time and memory when dynamic linking, since each .so file linked requires the filesystem operations to locate and find it, and a few pages for its static variables, relocations, etc.

An implementation where all functions are in one library and the -lm, -lpthread, -lrt, etc. options are all no-ops (or link to empty .a files) is perfectly POSIX conformant and certainly preferable.

Note: I'm talking about POSIX because C itself does not specify anything about how the compiler is invoked. Thus you can just treat gcc -std=c99 -lm as the implementation-specific way the compiler must be invoked for conformant behavior.

这篇关于gcc:为什么需要-lm标志来链接数学库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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