C 编译失败:找不到 math.h 函数 [英] C Failing to compile: Can't find math.h functions
问题描述
我正在编写一个质数查找器.在数学上,它比执行 for (unsigned long i = 2; i < number/2; i++)
快得多,而且仍然同样有效,执行 for (unsigned long i = 2; i
I'm writing a prime number finder. Mathematically, it is faster to, instead of doing for (unsigned long i = 2; i < number/2; i++)
it's a lot faster, and still just as effective, to do for (unsigned long i = 2; i < sqrt(number); i++)
但它不起作用.下面是我的代码.
But it's not working. The below is my code.
// Stuff goes up here, including a function prototype and:
#include <math.h>
char isPrime (unsigned long number)
{
if (number <= 1) {
return 0;
}
long double sqrtOfNumber = sqrt(number); // Calculate once.
for (unsigned long i = 2; i < sqrtOfNumber; i++) {
if (number%i == 0) { // It has a divisor.
return 0;
}
}
// Nothing broke us yet....
return 1;
}
然后下面是我从 GCC 得到的错误.
And then below is the error I get from GCC.
/tmp/ccFBlUz5.o: In function `isPrime':
main.c:(.text+0xb3): undefined reference to `sqrt'
collect2: error: ld returned 1 exit status
将数字"的类型更改为双精度会导致 % 运算符出现问题.并且为 sqrt() 调用将其转换为 double 不会改变任何内容.
Changing the type of "number" to a double causes problems with the % operator. And casting it to a double for the sqrt() call doesn't change anything.
有什么建议吗?
哦,我的 math.h 正在导入,如果我注释掉那行,我会收到警告,那里有一个隐式声明.
Oh, and my math.h IS being imported, if I comment out that line, I get warned that there is an implicit declaration there.
main.c: In function 'isPrime':
main.c:28:2: warning: implicit declaration of function 'sqrt' [-Wimplicit-function-declaration]
long double sqrtOfNumber = sqrt(number); // Calculate once.
^
main.c:28:29: warning: incompatible implicit declaration of built-in function 'sqrt' [enabled by default]
long double sqrtOfNumber = sqrt(number); // Calculate once.
^
加上其他警告.
推荐答案
-lm
需要在需要该库的文件之后添加到命令行,例如如果 main.c
需要数学库,然后您将使用:
-lm
needs to added to the command line after the file that requires that library for example if main.c
required the math library then you would use:
gcc -x c main.c -lm
您可以在此处看到一个实时示例,在例子.一个没有-lm
,一个在需要它的文件之前有一个-lm
,一个在需要它的文件之后.
You can see a live example here, there are three command lines available in the example. One without -lm
, one with -lm
before the file that needs it one after the files that needs it.
为了完整起见,如果我们参考 关于链接选项的 gcc 文档 它对 -l
表示以下内容:
For completeness sake if we refer to the gcc docs on options for Linking it says the following for -l
:
[...]在命令中编写此选项的位置有所不同;链接器按照指定的顺序搜索和处理库和目标文件.因此,‘foo.o -lz bar.o’在文件 foo.o 之后但在 bar.o 之前搜索库‘z’.如果 bar.o 引用z"中的函数,则可能不会加载这些函数.[...]
[...]It makes a difference where in the command you write this option; the linker searches and processes libraries and object files in the order they are specified. Thus, ‘foo.o -lz bar.o’ searches library ‘z’ after file foo.o but before bar.o. If bar.o refers to functions in ‘z’, those functions may not be loaded. [...]
这篇关于C 编译失败:找不到 math.h 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!