当前位置:网站首页>C语言中以static说明符开头的变量和函数具有的性质
C语言中以static说明符开头的变量和函数具有的性质
2022-07-21 15:11:00 【小飞将】
如果使用了static说明符,则标识符的第一个外部声明将使得改标识符具有内部连接,内部链接的标识符只在当前的.c源文件(transilation Unit,翻译单元)可见,即只在当前的.c源文件可见,其他源文件不可见。
声明的全局变量,如果只在当前的.c文件(transilation Unit,翻译单元)中使用,不会在别的.c文件中使用,此时在.c而不是.h文件中用static声明;如果声明的全局变量会在别的.c文件中使用,那么将其声明为extern的,并放在.h文件中。除了extern的外部变量在头文件中声明外,不要在头文件中声明任何变量。 否则在源文件中展开头文件时,可能会有多次变量声明。更不要在头文件中定义变量。
参考Stack Overflow:https://stackoverflow.com/questions/1856599/when-to-use-static-keyword-before-global-variables
声明的全局函数,如果只在当前的.c文件中使用,不希望外部访问,则声明为static类型。
C语言函数定义默认为全局的,而声明为static的函数只在当前.c文件中可见,其他.c文件不可见;可以在别的.c文件中重新定义同名的函数。
example:
static_fun.h
#pragma once
#include <stdio.h>
static void static_fun();
void fun();
void printfun();
static_fun.c
#include "static_fun.h"
static int static_variable = 1;
static void static_fun() {
printf("Static fun call\n");
}
void fun() {
printf("Global fun call\n");
static_fun();
}
void printfun() {
printf("static variable is: %d\n", static_variable);
}
main.c
#include "static_fun.h"
int main()
{
// static function/variable call test
static_fun(); // error: static function decleared but not defined
fun(); // OK: extern function
printf("Static variable: %d\n", static_variable); // error: static_variable not defined
printfun(); // OK: access static variable by extern function
return 0;
}
static_fun()只在static_fun.c中可见,所以main.c中static_fun();调用被当做声明,但是未找到函数定义;
printf static_variable的静态变量只在static_fun.c中可见,所以变量未定义;
可以通过外部函数来间接地访问静态变量或者函数。
static关键字的这一特性在C语言中经常用于设计实现ADT (Abstract Data Type),例如链表,树等抽象数据结构。static声明的函数和变量都只在ADT内部可见,外部无法访问。
void func() {
static int val = 1;
++val;
printf("static value: %d\n", val);
}
int main()
{
func();
func();
return 0;
}
static value: 2
static value: 3
两次调用含有static的函数,第二次定义没有生效,也没有发生静态变量重新初始化,程序执行到静态变量处,它的值仍然是上一次的结果。
边栏推荐
- Foundation of Mathematics: Lagrangian optimization and duality
- When running, the object moves, rotates and scales the plug-in, "runtimetransformgizmos plug-in" tutorial (unity3d)
- Jmeter安装与设置(一)
- ps小白從0開始……
- win10下载地址
- Airtest stepped on the pit -- start flash back
- 模板方法模式
- 笔记本电脑选购指南(不推荐具体品牌及型号)
- 实现逐行输出文本文件的内容
- 高通与苹果和解,获得至少45亿美元和解费!下一个目标:华为!
猜你喜欢
随机推荐
跨服器,插入,查寻
【MATLAB问题解决】解决Matlab编译后的.exe文件在另一台电脑上无法运行的问题
Common commands for starting services
vi编辑器常用命令
地理卫星数据下载
Codeforces Round #690 (Div. 3) C. Unique Number 常规解法
Envi band synthesis inverse operation -- band splitting
微信小程序列表(数据渲染之列表渲染)
Assembler Instructions with C Expression Operands
flask - { “message“: “Failed to decode JSON object: Expecting value: line 1 column 1 (char 0)“ }
【数学基础】 foundation of mathematics :拉格朗日优化和对偶
Awvs installation and problem solving
Foundation of Mathematics: Jensen inequality
第三版新视野大学英语读写教程4结业考点(1,2,3,5,6单元)
Codeforces Round #690 (Div. 3) B. Last Year‘s Substring 常规解法
Chrome升级到80版本遇到的问题-系统登录不了的解决方法
709. 转换成小写字母
Device eth3 does not see to be present, delaying initialization
敬伟PS教程:基础篇A
ENVI栅格重采样