gpt4 book ai didi

代码块编译我的程序与命令中的 gcc 不同

转载 作者:太空狗 更新时间:2023-10-29 16:11:35 26 4
gpt4 key购买 nike

我今天试图检查一个答案,我意识到如果我使用代码块(使用 gcc),我必须处理与使用 gcc 的命令行(Ubuntu Linux)不同的错误。

程序是这样的:

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

int main(void){
double len,x,y =0;
int n=123456;

len=floor(log10(abs(n))) + 1;

x = n / pow(10, len / 2);
y = n - x * pow(10, len / 2);

printf("First Half = %f",x);
printf("\nSecond Half = %f",y);

return 0;
}

如果我尝试编译它,我会得到:

error: implicit declaration of function ‘abs’ [-Werror=implicit-function-declaration]|

所以有趣的是。我在Compiler => global compiler => settings => Other settings中加了-lm,结果还是一样。

只有当我包含 stdlib.h 时它才有效。

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

int main(void){
double len,x,y =0;
int n=123456;

len=floor(log10(abs(n))) + 1;

x = n / pow(10, len / 2);
y = n - x * pow(10, len / 2);

printf("First Half = %f",x);
printf("\nSecond Half = %f",y);

return 0;
}

但是如果我使用命令行(在终端中)使用命令:

   gcc program.c -o program -lm

程序编译成功。

我的问题:为什么会这样?我在interent上做了一个研究,发现有人说abs函数是在stdlib.h中声明的,而不是在ma​​th.h中声明的。但是如果我在命令行中编译(不包括 stdlib.h),-lm 工作。我很困惑。

最佳答案

简答:试试

gcc -Wall -Wextra -pedantic -o program -lm

gcc -Wall -Wextra -Werror -pedantic -o program -lm

让它在出现警告时失败,就像 Codeblocks 似乎做的那样。

长答案:链接到库与包含头文件是完全不同的事情。在 C 中,由于历史原因,“允许”使用声明的函数。在这种情况下,编译器假定一个函数返回 int 并接受您提供的任何参数。对于 abs(),这些假设成立。所以稍后,链接器在与 libm 链接时找到函数,一切正常。

但是有很多问题:首先,如果您不启用警告,您将错过简单的拼写错误。其次,编译器无法检查您提供的参数 -> 提前使程序崩溃。如果该函数确实返回 int 以外的内容,则会出现更多问题。

abs()stdlib.h 中声明。要使用它,请包含此 header 。并且始终启用编译器警告(Codeblocks 显然会为您完成)。

关于代码块编译我的程序与命令中的 gcc 不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32019532/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com