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這個文件不存在。