C 编程语言一书描述了静态变量的用法,主题what-does-static-mean-in-a-c-program
- A static variable inside a function keeps its value between invocations.
- A static global variable or a function is "seen" only in the file it's declared in
和书上解释的一样,但是第1点可以,第2点不可以。
我的代码:
标题.h
static int VAL = 15;
int canShare = 1;
static void hello(char c) {
printf("header file -> VAL: %d\n", VAL);
printf("header file -> canShare: %d\n", canShare);
printf("hello func -> %d\n", c);
}
主程序
#include <stdio.h>
#include "header.h"
main() {
printf("main -> VAL: %d\n", VAL+1);
printf("main -> canShare: %d\n", canShare+1);
hello('A');
}
输出
main -> VAL: 16
main -> canShare: 2
header file -> VAL: 15
header file -> canShare: 1
hello func -> 65
最佳答案
解释中存在细微的错误:
A static global variable or a function is "seen" only in the file it's declared in.
它仅在声明的翻译单元中可用。#include
指令字面上将头文件包含到翻译单元中,因此 TU 包含包含的头文件(如你可能会期望,语法上)。
关于c - c中函数和变量的静态作用域使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18928328/