Chinaunix首页 | 论坛 | 博客
  • 博客访问: 404139
  • 博文数量: 65
  • 博客积分: 1491
  • 博客等级: 上尉
  • 技术积分: 702
  • 用 户 组: 普通用户
  • 注册时间: 2009-05-30 15:57
文章分类
文章存档

2011年(6)

2010年(12)

2009年(47)

我的朋友

分类: C/C++

2009-06-08 19:39:23

在C/C++中, 局部变量按照存储形式可分为三种auto, static, register.
static关键字是C, C++中都存在的关键字, 它主要有三种使用方式, 详细用法参见文章:http://blog.chinaunix.net/u3/93782/showart_1951616.html
 
本文主要是分析static修饰函数时的作用:
 
(1) static修饰符可以使函数仅在当前模块(文件)中有效,外部模块无法调用static修饰的函数;
如果全局存在同名的函数,则static会屏蔽掉全局函数,相当于在当前模块中重载这个函数.
 
例如hello.c 和 main.c 两个文件中的 helloworld() 函数.
这个程序的输出结果是:I am static.
 

/* 文件hello.c: */
#include <stdio.h>
void helloworld()
{
    printf("Hello World!""\n");
}

/* 文件main.c: */
#include <stdio.h>
static void helloworld()
{
    printf("\nI am static.\n");
}
int main()
{
    helloworld();
    return 0;
}

(2) 以上面的两个源文件为例,如果在main函数中去掉static关键字(修饰符),或者添加一行"extern void helloworld", gcc在编译时都会出错:multiple definition of `helloworld'.补充一点,没有static修饰的函数默认是extern的.
 

(3) static修饰符的应用难点在于“多线程编程”和“面向对象编程”. 本文不对此进行分析.

<--文章完-->
阅读(2591) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~