目录
1.1.1 以helloworld为例,对写程序的思路提出以下要求:
1.1 基本概念
1.1.1 以helloworld为例,对写程序的思路提出以下要求:
- 头文件正确包含的重要性。
包含头文件
#include <stdio.h>
//#include <stdlib.h>
int main(int argc,char *argv[])
{
int *p = NULL;
int i ;
p = malloc(sizeof(int));
if(p == NULL)
return -1;
printf("Hello world!\n");
return 0;
}
malloc返回的是void*类型的指针。代码中直接赋值给了 int* 类型的指针p。
如果直接gcc hello.c -Wall 。(-iWall 表示打印所有警告),会出现
gcc hello.c,会出现警告
hello.c: In function ‘main’:
hello.c:8:6: warning: implicit declaration of function ‘malloc’ [-Wimplicit-function-declaration]
p = malloc(sizeof(int));
^~~~~~
hello.c:8:6: warning: incompatible implicit declaration of built-in function ‘malloc’
hello.c:8:6: note: include ‘<stdlib.h>’ or provide a declaration of ‘malloc’gcc hello.c -Wall 。会出现更多警告
hello.c: In function ‘main’:
hello.c:9:6: warning: implicit declaration of function ‘malloc’ [-Wimplicit-function-declaration]
p = malloc(sizeof(int));
^~~~~~
hello.c:9:6: warning: incompatible implicit declaration of built-in function ‘malloc’
hello.c:9:6: note: include ‘<stdlib.h>’ or provide a declaration of ‘malloc’
hello.c:7:6: warning: unused variable ‘i’ [-Wunused-variable]
int i;
^在源文件增加 #include<stdlib.h>,去掉int i; 后,执行 gcc hello.c -Wall。 不再出在警告和错误提示。
如果一个函数,没有看到原型,默认该函数的返回值是int类型。
因为程序中没有包含#include<stdlib.h>,程序认为malloc()返回值是整型,将一个整型值复制给一个int*。会报错。
强制转换 p = (int *)malloc(); gcc hello.c -Wall 。就不报错了。但是这里有问题,没有解决根本问题,实际上是在掩盖问题。解决方式应该是增加头文件。
(在有的编译器(QNX系统开发)中,增加了头文件,没有强制转换,也会报错。保险方式是既增加头文件,又强制转换。在Linux中,只增加头文件,就不会报错。)
写程序的时候要把所有的警告都调试完。
有时程序会提示段错误,此时可以-Wall打印所有警告,所有警告都调完,十有八九段错误也解决了。
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
//#include <string.h>
int main(int argc,char *argv[])
{
FILE *fp;
fp = fopen("tmp","r");
if(fp == NULL)
{
fprintf(stderr,"fopen():%s\n",strerror(errno));
exit(1);
}
puts("ok!");
exit(0);
}
编译出现警告,但依然生成可执行文件。但是当执行可执行文件时,出现段错误的提示
通过增加#include<string.h>,可以解决此问题。