gcc 在使用 fmod() 时出错
fmod 的示例代码:
#include <stdio.h>
#include <math.h>
int main(void)
{
double x = 0.14527, y = 3.14159;
printf("fmod(x, y) = %.6lf\n", fmod(x, y));
return 0;
}
编译:
$ gcc main.c -o main
我明白了
/tmp/ccztJO01.o:在函数“main”中:
main.c:(.text+0x4d): 对“fmod”的未定义引用
collect2: ld 返回 1 退出状态
然后我在 Google 中找到了这个:
$ gcc -lm main.c -o main
Why should I use -lm
,它到底是什么?从哪里可以获得有关 gcc 的详细信息?
Sample code for fmod:
#include <stdio.h>
#include <math.h>
int main(void)
{
double x = 0.14527, y = 3.14159;
printf("fmod(x, y) = %.6lf\n", fmod(x, y));
return 0;
}
Compiling:
$ gcc main.c -o main
I get
/tmp/ccztJO01.o: In function `main':
main.c:(.text+0x4d): undefined reference to `fmod'
collect2: ld returned 1 exit status
Then I found this in Google:
$ gcc -lm main.c -o main
Why should I use -lm
, what is it exactly? From where I can get more information about gcc in detail?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
-lm
只是告诉它链接libm
,其中包含所有浮点数学例程,包括(毫不奇怪)fmod
。-lm
is simply telling it to linklibm
, which contains all the floating point math routines, including (no surprise here)fmod
.当我输入
gcc -lm main.c -o main
时,我仍然收到链接器错误。我需要编写gcc main.c -lm -o main
才能正常工作。如果它以另一种方式为你工作,那就有点奇怪了。我知道链接器会找到 main.c 中声明的符号(即 double fmod(double,double) ),但只有在稍后找到其定义时才解析它(即在 libm 中) .a)。长话短说,库必须放置(至少一次)在使用位置的“右侧”。
When I input
gcc -lm main.c -o main
I still get a linker error. I need to writegcc main.c -lm -o main
for it work right. If it's working for you the other way, that's a bit odd. I understand that the linker will find the symbol declared in main.c (i.e.double fmod(double,double)
), but only resolve it if it finds its definition later on (i.e. inlibm.a
).Long story short, the libraries must be placed (at least once) "to the right of" the place where they are used.
抱怨的不是编译器,而是链接器,
ld
。它在您的程序中找不到例程fmod
。您必须告诉它使用-l
标志与数学库libm
链接。[更多]更多信息:GCC,GNU 编译器集合。
It's not the compiler, but the linker,
ld
, that is complaining. It cannot find the routinefmod
in your program. You have to tell it to link with math librarylibm
with the-l
flag.[Much] more info: GCC, the GNU Compiler Collection.