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」在函數聲明中無關緊要,只是用來標誌該函數在本文件中定義,仍是在別的文件中定義。只要你函數在使用以前聲明瞭,那麼就能夠不用包含頭文件了。

相關文章
相關標籤/搜索