我试图执行一个使用数学库的文件(更具体地说,它使用的是 sqrt() 函数)。所以我输入了 gcc fileName.c -o fileName,它一直说“未定义对‘sqrt’的引用”。但是当我在谷歌上搜索时,有人说在我的 gcc 调用结束时添加 -lm ,但我不明白为什么,有人能解释一下吗?谢谢。
山姆
添加-lm
告诉 gcc 链接到数学库。
-l<name> link against the library with name <name>
C 编译有两个不同的步骤:编译为目标代码和链接。在编译为目标代码时,文件按原样编译,并且任何外部符号(例如通过包含标头获得的符号)都保留为“空白”。下一个阶段,链接,是填充这些空白的地方。对于许多库,您必须告诉 gcc 在哪里查找,因此您必须给出一个-l
标志(在这种情况下,-lm
用于数学)。
Strictly you need -lm
in the invocation of the linker (ld) rather than the compiler, but gcc can invoke the linker after compilation and will forward the argument. In more complex projects, you would invoke the linker separately.
The command line options for the linker are described here, while those for the compiler are described here.
The option -l
namespec links the static library named lib*namespec*.a, whereas -l:
filename, links the library filename. An alternative form --library=
namespec or --library=
filename is supported.
-lm
links libm.a - the math library. The non math part of the standard library is in libc.a, but this is normally linked by default so i snot specified explicitly.