为什么在 Math.h 中调用函数时出现链接错误? [英] Why Am I Getting Link Errors When Calling Function in Math.h?

查看:15
本文介绍了为什么在 Math.h 中调用函数时出现链接错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试调用 math.h 中的函数时,我收到如下链接错误

When attempting to call functions in math.h, I'm getting link errors like the following

undefined reference to sqrt

但我正在做一个 #include <math.h>
我正在使用 gcc 并编译如下:

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

为什么链接器找不到sqrt的定义?

Why can't the linker find the definition for sqrt?

推荐答案

调用gcc时在命令中添加-lm:
gcc -Wall -D_GNU_SOURCE blah.c -o blah -lm

Add -lm to the command when you call gcc:
gcc -Wall -D_GNU_SOURCE blah.c -o blah -lm

这将告诉链接器链接到数学库.包含 math.h 将告诉编译器存在诸如 sqrt() 之类的数学函数,但它们定义在单独的库中,链接器需要将其与可执行文件一起打包.

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.

正如 FreeMemory 指出的那样,该库称为 libm.a .在类 Unix 系统上,命名库的规则是 lib[blah].a .然后,如果您想将它们链接到您的可执行文件,请使用 -l[blah] .

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屋!

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