C 程序编译错误处理:undefined reference to sqrtf
最近在写程序编译时,遇到了一个在 Windows 下的 IDE 里可以编译通过,放到 Linux 上就编译不过去的问题,简单记录下。
问题重现
编译 C 程序时出现了undefined reference to 'sqrtf'
错误,如下所示:
init_position.o: In function 'init_position(Files*, Para*, Data*)':
init_position.cpp:(.text+0x6bf): undefined reference to 'sqrtf'
原因
程序中调用 math.h
标准库中的 sqrt
函数(实际上与使用什么函数无关),在编译时却没有指出来,因而出错。
解决
编译时添加 -lm
参数即可,即告诉编译器这个程序使用了 math
库。实际上,可以通过运行 man sqrtf
知道要 "Link with -lm."
SQRT(3) Linux Programmer's Manual SQRT(3)
NAME
sqrt, sqrtf, sqrtl - square root function
SYNOPSIS
#include <math.h>
double sqrt(double x);
float sqrtf(float x);
long double sqrtl(long double x);
Link with -lm.
...
...