c static

c static

 

 

static external variable/function:

only visible in local file,

you can define multiple static variable in different source file, and there will be no conflict,

 

static local variable:

variable only init once, and keep the value among multiple function calls,

 

variable default value:

int type default to 0,

 

variable store location:

store in static storage,

 

------

no extern for static

 

you should not use extern on static variable/function,


------
code:

ab.h:
// use extern to declare variable / function
extern int xa;
extern void fone();
extern void fxs();
 
a.c:
#include <stdio.h>
#include "ab.h"

// define variable xa
int xa = 10;

// static variable, only visible to local file
static int xs = 10;

// static function, only visible to local file
static void fxs2() {
	printf("%d\n", xs);
}

void ftwo() {
	// static local variable, default to 0, the init clause only execute once among multiple function calls,
	static int localx;
	static int localy=1000;
	printf("%d,%d\n",localx++,localy++);
}

main() {
	// use function that declare by extern
	fone();
	printf("%d,%d\n",xa, xs);
	fxs();
	fxs2();
	int i;
	for(i=0;i<5;i++) {
		ftwo();
	}
}
 
b.c:
#include <stdio.h>
#include "ab.h"

// static variable, only visible to local file
static int xs = 11;

// define function fone()
void fone() {
	// use variable that declare by extern
	xa = 11;
}
void fxs() {
	printf("%d\n",xs);
}

// static function, only visible to local file
static void fxs2() {
	fxs();
}

command to compile:
gcc a.c b.c

run:
./a.out

------

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值