C语言基础 -3 基本概念,头文件的重要性

wesley@ubuntu:~/c$ cat hello.c
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
        int *p = NULL;

        p = (int *)malloc(sizeof(int));
        if(p == NULL)
                exit(1);

        printf("Hello World/n");

        exit(0);
}
wesley@ubuntu:~/c$ sudo gcc hello.c
wesley@ubuntu:~/c$ ls
a.out  hello.c
wesley@ubuntu:~/c$ sudo gcc hello.c -Wall   # 通报警告

mellaoc包含在 <stdlib.h>库中,使用melloc,应该包含该头文件<stdlib.h>

写c代码,要调试到gcc xxx.c -Wall 没有警告为止

wesley@ubuntu:~/c$ sudo vi test.c
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

int main()
{
        FILE *fp;

        fp = fopen("tmp","r");
        if(fp == NULL)
        {
                fprintf(stderr,"fopen():%s\n",strerror(errno));
                exit(1);
        }
        puts("ok!");
        exit(0);

}
wesley@ubuntu:~/c$ sudo gcc test.c
test.c: In function ‘main’:
test.c:12:3: warning: format ‘%s’ expects argument of type ‘char *’, but argument 3 has type ‘int’ [-Wformat=]
   fprintf(stderr,"fopen():%s\n",strerror(errno));
   ^
wesley@ubuntu:~/c$ 

上面报错,最根本原因是因为有一个包没有被包含。使用了%s,但%s对应的string.h没有被包含。

wesley@ubuntu:~/c$ sudo vi test.c
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

int main()
{
        FILE *fp;

        fp = fopen("tmp","r");
        if(fp == NULL)
        {
                fprintf(stderr,"fopen():%s\n",strerror(errno));  # 使用stderr,就要包含<errno.h>这一头文件
# 使用%s,就要包含<string.h>头文件
                exit(1);
        }
        puts("ok!");
        exit(0);                       # 使用exit,就要包含<stdlib.h>这一头文件

}                                                                                                                                                                                           
"test.c" 19L, 239C written    
                                                
wesley@ubuntu:~/c$ sudo gcc test.c
wesley@ubuntu:~/c$ ls
a.out  hello.c  test.c
wesley@ubuntu:~/c$ ./a.out
fopen():No such file or directory     # 此处报错是因为tmp这个文件不存在。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章