在Math.h中调用函数时为什么会出现链接错误? [英] Why Am I Getting Link Errors When Calling Function in Math.h?
问题描述
当试图在 math.h
中调用函数时,我得到如下的链接错误:
未定义的引用sqrt
但是我做了一个 #include
我使用gcc并编译如下:
gcc -Wall -D_GNU_SOURCE blah.c -o blah
为什么连接器不能找到 sqrt
?的定义?
当您调用gcc时,将-lm添加到命令中:
gcc -Wall -D_GNU_SOURCE blah.c -o blah -lm
这会告诉链接器与数学库链接。包括math.h会告诉编译器像sqrt()这样的数学函数存在,但它们是在单独的库中定义的,链接器需要用你的可执行文件打包。
< FreeMemory指出这个库叫做libm.a。在类Unix系统上,命名库的规则是lib [blah] .a。那么如果你想将它们链接到你的可执行文件,你可以使用-l [blah]。
When attempting to call functions in math.h
, I'm getting link errors like the following
undefined reference to sqrt
But I'm doing a #include <math.h>
I'm using gcc and compiling as follows:
gcc -Wall -D_GNU_SOURCE blah.c -o blah
Why can't the linker find the definition for sqrt
?
Add -lm to the command when you call gcc:
gcc -Wall -D_GNU_SOURCE blah.c -o blah -lm
This will tell the linker to link with the math library. Including math.h will tell the compiler that the math functions like sqrt() exist, but they are defined in a separate library, which the linker needs to pack with your executable.
As FreeMemory pointed out the library is called libm.a . On Unix-like systems, the rule for naming libraries is lib[blah].a . Then if you want to link them to your executable you use -l[blah] .
这篇关于在Math.h中调用函数时为什么会出现链接错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!