【问题标题】:C Failing to compile: Can't find math.h functions [duplicate]C编译失败:找不到math.h函数[重复]
【发布时间】:2013-10-15 02:06:34
【问题描述】:

我正在编写一个质数查找器。从数学上讲,使用for (unsigned long i = 2; i < number/2; i++) 比使用for (unsigned long i = 2; i < number/2; i++) 更快,而且仍然同样有效,而不是使用for (unsigned long i = 2; i < sqrt(number); i++)

但它不起作用。以下是我的代码。

// 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 得到的错误。

/tmp/ccFBlUz5.o: In function `isPrime':
main.c:(.text+0xb3): undefined reference to `sqrt'
collect2: error: ld returned 1 exit status

将“数字”的类型更改为双精度会导致 % 运算符出现问题。并且为 sqrt() 调用将其转换为 double 不会改变任何内容。

有什么建议吗?

哦,我的 math.h 正在被导入,如果我注释掉那行,我会收到警告说那里有一个隐式声明。

    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.
                         ^

加上其他警告。

【问题讨论】:

  • 你是怎么编译的?在终端还是在 IDE 中?
  • 短语undefined reference to sqrt 是你的线索。头文件提供了原型(否则错误会有所不同)。现在,您的程序需要 .lib 中提供的函数定义。你必须把它链接进去。

标签: c gcc


【解决方案1】:

-lm 需要在需要该库的文件之后添加到命令行,例如,如果 main.c 需要数学库,那么您将使用:

 gcc -x c main.c -lm 

您可以看到一个实时示例here,示例中提供了三个命令行。一种没有-lm,一种在需要它的文件之前有-lm,一种在需要它的文件之后。

为了完整起见,如果我们参考gcc docs on options for Linking,它对-l 表示以下内容:

[...]在命令中编写此选项的位置有所不同;链接器按照指定的顺序搜索和处理库和目标文件。因此,“foo.o -lz bar.o”在文件 foo.o 之后但在 bar.o 之前搜索库“z”。如果 bar.o 引用了“z”中的函数,则可能不会加载这些函数。 [...]

【讨论】:

    【解决方案2】:

    您需要链接数学库。在命令行上使用-lm 选项。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-04
      • 1970-01-01
      • 2018-08-02
      • 2021-12-26
      • 2015-04-25
      相关资源
      最近更新 更多