为什么必须在 C 中链接数学库? [英] Why do you have to link the math library in C?

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

问题描述

如果我在 C 程序中包含 <stdlib.h> 我不需要在编译时链接这些但我这样做必须链接到 ,使用 -lm 和 gcc,例如:

If I include <stdlib.h> or <stdio.h> in a C program I don't have to link these when compiling but I do have to link to <math.h>, using -lm with gcc, for example:

gcc test.c -o test -lm

这是什么原因?为什么我必须显式链接数学库而不是其他库?

What is the reason for this? Why do I have to explicitly link the math library but not the other libraries?

推荐答案

stdlib.hstdio.h 中的函数在 libc.so 中有实现(或 libc.a 用于静态链接),默认情况下链接到您的可执行文件(就像指定了 -lc 一样).可以使用 -nostdlib-nodefaultlibs 选项指示 GCC 避免这种自动链接.

The functions in stdlib.h and stdio.h have implementations in libc.so (or libc.a for static linking), which is linked into your executable by default (as if -lc were specified). GCC can be instructed to avoid this automatic link with the -nostdlib or -nodefaultlibs options.

math.h 中的数学函数在 libm.so(或用于静态链接的 libm.a)和 中有实现>libm 默认不链接.这种 libm/libc 分裂是有历史原因的,没有一个很有说服力.

The math functions in math.h have implementations in libm.so (or libm.a for static linking), and libm is not linked in by default. There are historical reasons for this libm/libc split, none of them very convincing.

有趣的是,C++运行时libstdc++需要libm,所以如果你用GCC(g++)编译C++程序,你会自动得到libm 已链接.

Interestingly, the C++ runtime libstdc++ requires libm, so if you compile a C++ program with GCC (g++), you will automatically get libm linked in.

这篇关于为什么必须在 C 中链接数学库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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