C中extern的用法

/*
**********************************************************************数组

INPUT3.C -- Input data parser for EPANET;app

VERSION:    2.00
DATE:       5/30/00
            9/7/00
            10/25/00
            3/1/01
            6/24/02
            8/15/07    (2.00.11)
            2/14/08    (2.00.12)
AUTHOR:     L. Rossman
            US EPA - NRMRLdom

This module parses data from each line of input from file InFile.
All functions in this module are called from newline() in INPUT2.C.
该模块逐行解析INPUT文件。
该模块中的全部函数都在INPUT2.C的newline(int sect, char *line)中被调用。函数

**********************************************************************
*/this

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include <math.h>
#include "hash.h"
#include "text.h"
#include "types.h"
#include "funcs.h"
#define  EXTERN  extern
#include "vars.h"blog

/* Defined in enumstxt.h in EPANET.C */
extern char *MixTxt[];
extern char *Fldname[];            //字段名称字符串数组token

/* Defined in INPUT2.C */
extern char      *Tok[MAXTOKS];    //
extern STmplist  *PrevPat;
extern STmplist  *PrevCurve;
extern int       Ntokens;字符串

...get

----------------------------------------------------input

http://www.cnblogs.com/KingOfFreedom/admin/EditPosts.aspx?opt=1

extern

 

   在源文件A里定义的函数,在其它源文件里是看不见的(即不能访问)。为了在源文件B里能调用这个函数,应该在B的头部加上一个外部声明:

 

   
  extern   函数原型;   

 


  这样,在源文件B里也能够调用那个函数了。  
  注意这里的用词区别:在A里是定义,在B里是声明。一个函数只能(也必须)在一个源文件里被定义,可是能够在其它多个源文件里被声明。定义引发存储分配,是真正产生那个实体。而声明并不引发存储分配。打一个粗俗的比方:在源文件B里声明后,比如在B里开了一扇窗,让它能够看到A里的那个函数。

 

 

 

  1.extern用在变量声明中经常有这样一个做用,你在*.c文件中声明了一个全局的变量,这个全局的变量若是要被引用,就放在*.h中并用extern来声明。  2.若是函数的声明中带有关键字extern,仅仅是暗示这个函数可能在别的源文件里定义,没有其它做用。即下述两个函数声明没有区别:  extern int f(); 和int f();   ================================  若是定义函数的c/cpp文件在对应的头文件中声明了定义的函数,那么在其余c/cpp文件中要使用这些函数,只须要包含这个头文件便可。  若是你不想包含头文件,那么在c/cpp中声明该函数。通常来讲,声明定义在本文件的函数不用“extern”,声明定义在其余文件中的函数用“extern”,这样在本文件中调用别的文件定义的函数就不用包含头文件  include “*.h”来声明函数,声明后直接使用便可。  ================================  举个例子:  //extern.cpp内容以下:    // extern.cpp : Defines the entry point for the console application.  //    #i nclude "stdafx.h"  extern print(char *p);  int main(int argc, char* argv[])  {   char *p="hello world!";   print(p);   return 0;  }  //print.cpp内容以下  #i nclude "stdafx.h"  #i nclude "stdio.h"  print(char *s)  {   printf("The string is %s/n",s);  }    结果程序能够正常运行,输出结果。若是把“extern”去掉,程序依然能够正常运行。    因而可知,“extern”在函数声明中无关紧要,只是用来标志该函数在本文件中定义,仍是在别的文件中定义。只要你函数在使用以前声明了,那么就能够不用包含头文件了。

相关文章
相关标签/搜索