static 与 extern
来源:互联网 发布:单片机push 编辑:程序博客网 时间:2024/05/01 17:06
下面根据自己对static与extern的理解,说明一下:
变量的不同类型,决定了其生命周期及其作用域。
extern:
extern 可以用来修饰变量,也可以用来修饰函数。
1、对于函数来说,既可以是声明一个外部函数,也可以是定义一个函数;有两个源文件man.c和test.c如下:
例子1、
源文件 test.c
// test.c #include <stdio.h> void test() { printf("我是来自源文件test.c中的test函数!"); }
源文件 main.c
//main.c #include <stdio.h> extern void test(); //声明一个外部函数test int main() { test(); //调用test.c中的函数test return 0; }
例子2、
源文件 test.c
// test.c #include <stdio.h> extern void test() //定义一个函数 { printf("我是来自源文件test.c中的test函数"); }
源文件 main.c
// main.c#include <stdio.h> extern void test(); //声明一个外部函数test int main() { test(); //调用test.c中的函数test return 0; }
2、对于变量来说,只能用来声明变量而不可以定义变量;有两个源文件man.c和test.c如下:
源文件test.c
//test.c #include <stdio.h> int a; //定义一个变量a void test () { printf("a = %d",a); }
源文件main.c
//main.c #include <stdio.h> extern int a; //声明一个外部变量a ,这里不是定义变量 extern void test(); //声明一个外部函数test int main() { a = 10; test(); return 0; }
static:
static 可以用来修饰变量,也可以用来修饰函数。
1、对于函数来说,可以定义一个内部函数;有两个源文件man.c和test.c如下:
源文件test.c
//test.c #include <stdio.h> static void test() //定义一个内部函数 { printf("我是test.c中的内部函数,其他文件无法访问。"); }
源文件main.c
//main.c #include <stdio.h> extern void test(); //声明一个外部函数test,以便main.c文件可以访问 int main() { test(); //这里调用外部函数test return 0; }
这里编译是没有错误,运行时就会报错,因为main中的test()函数找不到定义。
2、对于变量来说,可以定义一个内部变量;有两个源文件main.c和test.c如下:
源文件test.c
//test.c #include <stdio.h> static int a; void test() { printf("a = %d",a); }
源文件main.c
//main.c #include <stdio.h> extern void test(); //声明一个外部函数test,以便main.c中可以访问 extern int a; //声明一个外部变量a,不是定义 int main() { a = 10; //对外部变量a进行赋值 test(); //调用外部函数 return 0; }
此时的运行结果是 : a = 0
因为在test.c中的变量a定义为内部变量,默认初始化为0.
extern :改变作用域
static :改变生命周期
声明:此博文源自 http://blog.csdn.net/shenyuanluo/article/details/47981441
如需转载,请说明博文出处。谢谢!
0 0
- c++ static与extern
- extern与static
- extern与static用法
- extern 与 static
- extern与static用法
- extern static与inline
- extern与static
- extern与static分析
- static 与 extern
- static 与 extern
- static与extern
- extern与static关键字
- static与extern
- static 与 extern
- static与extern
- static与extern
- extern与static用法
- extern与static用法(转)
- Cisco vWSA (virtual Web Security Appliance)
- API
- 配置虚拟域名
- 6174问题求解
- 给你一次机会面试架构师 你会问什么问题?
- static 与 extern
- Lingo学习心得&2014年研究生数模竞赛E题
- 关闭中断
- 数论题集
- 全局异常处理
- 编程之类 数字号码《-》单词之间的转换
- os.Open()和os.OpenFile()
- 自定义一个UIButton
- 切片A = 切片B