C语言下extern static用法一结,及C++下extern “C”的用法

来源:互联网 发布:java 转义字符 处理 编辑:程序博客网 时间:2024/05/16 19:47

extern 修饰变量或者函数表示得含义是,引用外部文件得变量或者函数。

如下:

    在file1.c中如下代码,

    #include <stdio.h>

    int nTest = 10;

    void FuncTest()

    {

         printf("FuncTest!/n");

    }

 

    在file2.c中如下代码,

 

    #include <stdio.h>

    extern int nTest;                 //表示引用,如果写成 extern int nTest = 15;//将会出错,这表示定义一个变量,引起重定义。

                                               //extern 修饰局部变量是不允许的。

    extern void FuncTest();

 

    void FuncFile2()

    {

          printf("FuncFile2!/n");

          FuncTest();

          printf("%d/n",nTest);

    }

extern修饰变量或者函数的意思并不是定义变量或者函数,而是表示引用外部变量或者外部函数。记住是<引用>哦。

 

static得用法有很多,这里只讲同extern相关的用法。

static修饰全局变量或者函数表示此函数是本地变量,或者本地函数,不允许其他文件对其进行引用(extern)。如果你那么做,你将得到错误。(-_-||)。

比如修改 file1.c

int nTest = 10;   --->  static int nTest = 10;

void FuncTest();  --->  static void FuncTest();

编译得时候会出现什么问题呢,请自己试验(-_-)!

 

 

extern “C” 是再C++下才使用得,如果是C就不需要使用。

extern “C” 是干嘛的?

extern “C” 是为了解决名称匹配而出现得,在C++和C编译生成的汇编码中,对于函数的名字处理过程不一样,从而同样的函数形成的函数名称确不一样。如果在C++下使用C函数,就必须显式的告诉连接器,你现在连接的不是C++函数,而是C的库函数。那怎么通知呢,那就要通过 extern “C” 对这个函数进行修饰,表示它是C函数。具体修饰如下:

extern “C” void Func_C();

 

如果有多个C函数,那么可以

extern “C”

{

      void Func_C1();

      void Func_C2();

      void Func_C3();

              .

              .

              .

};

 

再如果有一个C库,有C库得头文件,又如何呢? 假如C库得头文件是 testc.h,那么只需如下:

extern “C”

{

       #include "testc.h"

};

当然,你要记得加载库哦。

 

以上是一些总结,欢迎各位领导莅临检查,批评指正。