c - 警告 : incompatible implicit declaration of built-in function log2

标签 c compiler-errors logarithm

<分区>

所以我们在 C 中有这个程序,我们需要使用以 2 为底的对数函数,以获得 n 的以 2 为底的对数。 这是代码:

#include <math.h>

int partSize(int n) {
    return log2(n);
}

但是在编译时,它给了我们以下警告。

sim.c: In function partSize : sim.c:114: warning: incompatible implicit declaration of built-in function log2

这是我们使用的命令

 gcc $file -o $name.out -lm 

最佳答案

事情是这样的,在 99.99999% 的情况下,当有人说“这个世界可用的基本功能不起作用”时,他们是错的。当这个基本的东西坏掉的时候,有那么一小部分时间,某处已经有一支拿着干草叉的军队了。

#include <math.h>
#include <stdio.h>

int partSize(int n){
    return log2(n);
}

int main(int argc, char *argv[]) {
    int ret = -1;
    ret = partSize(16);
    printf("%d\n", ret);
    return 0;
}

编译:

 > gcc -std=c99 a.c -o log2.out -lm
 > ./log2.out 
 > 4

是的,它正在工作。

在 C 中,使用以前未声明的函数构成函数的隐式声明。在隐式声明中,返回类型为 int .所以错误告诉你 log2()未在您的代码中定义,这会导致您未发布的代码出现问题。

当我跳过 -lm我得到:

a.c:(.text+0x11): undefined reference to `log2'
collect2: ld returned 1 exit status

..这看起来不对。好的,当我添加 -lm但删除 #include <math.h>我得到:

a.c: In function ‘partSize’:
a.c:5:5: warning: implicit declaration of function ‘log2’ [-Wimplicit-function-declaration]

嘿,这是你的警告!所以你可能是正确的,你包括了 -lm但出于某种原因 #include math.h有问题。可能是:

  1. 缺少 math.h
  2. 您并没有真正将它包含在文件中,例如,它是否在 #def 中并被编译出来?
  3. 您的 math.h 版本没有定义 log2

关于c - 警告 : incompatible implicit declaration of built-in function log2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16425279/

相关文章:

将 2 字节 char 数组转换为 int

r - 如何处理两个以上超小概率之和的log

c - 如何使用指向另一个字段的字段初始化结构?

c++ - 重新定义自定义删除

perl - 如何在Perl中为简单的I/O子例程创建单元测试

c - 警告 : passing argument 1 of ‘foo’ discards ‘const’ qualifier from pointer target type

java - 对数算法

python - Python 中的精确 math.log(x, 2)

c - 指针数组和地址间隔

c - Arduino - 如何将 char* 复制到 char**?