2025年3月28日 星期五 甲辰(龙)年 月廿七 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > C语言

什么时候说明函数?

时间:12-30来源:作者:点击数:97

只在当前源文件中使用的函数应该说明为内部函数(static),内部函数应该在当前源文件中说明和定义。对于可在当前源文件以外使用的函数,应该在一个头文件中说明,要使用这些函数的源文件要包含这个头文件。例如,如果函数stat_func()只在源文件stat.c中使用,应该这样说明:

  • /* stat.c */
  • # include <atdio.h>
  • atatic int atat_func(int,int); /* atatic declaration of atat-funcO */
  • viod main (void)
  • {
  • ......
  • rc=stat_func(1,2);
  • ......
  • }
  • /* definition (body) of stat-funcO */
  • static int stat-funcdnt argl,int arg2)
  • {
  • return rc;
  • }

在上例中,函数stat_func()只在源文件stat.c中使用,因此它的原型(或说明)在源文件stat.c以外是不可见的,为了避免与其它源文件中可能出现的同名函数发生冲突,应该将其说明为内部函数。

在下例中,函数glob_func()在源文件global.c中定义和使用,并且还要在源文件extern,c中使用,因此应该在一个头文件(本例中为proto.h)中说明,而源文件global.c和extern.c中都应包含这个头文件。

 File:  proto.h

  • /* proto.h */
  • int glob_func(int,int); /* declaration of the glob-funcO function */

 File:  global. c

  • /* global. c */
  • # include <stdio.h>
  • # include "proto. h" /*include this file for the declaration of glob_func() */
  • viod main (void)
  • {
  • rc_glob_func(l,2);
  • }
  • /* deHnition (body) of the glob-funcO function */
  • int glob_func(int argl,int arg2)
  • {
  • return rc;
  • }

File extern. c

  • /* extin.c */
  • # include <atdio.h>
  • # include "proto. h" /*include thia file for the declaration of glob_func() */
  • void ext_func(void)
  • {
  • /* call glob_func(), which ia deHncd in the global, c source file */
  • rc=glob_func(10,20);
  • }

在上例中,在头文件proto.h中说明了函数glob_func(),因此,只要任意一个源文件包含了该头文件,该源文件就包含了对函数glob_func()的说明,这样编译程序就能检查在该源文件中glob_func()函数的参数和返回值是否符合要求。请注意,包含头文件的语句总是出现在源文件中第一条说明函数的语句之前。

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门