3.3 Linux嵌入式C_基本概念-编程注意问题1

目录

1.1 基本概念

1.1.1 以helloworld为例,对写程序的思路提出以下要求:


1.1 基本概念

1.1.1 以helloworld为例,对写程序的思路提出以下要求:

  1. 头文件正确包含的重要性。

包含头文件

#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>,可以解决此问题。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值