Reputation: 11
The C Programming Language book describes static variable's usage, and the topic 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
explains the same as the book, but the point 1 can works and the point 2 can't work.
my code:
header.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);
}
main.c
#include <stdio.h>
#include "header.h"
main() {
printf("main -> VAL: %d\n", VAL+1);
printf("main -> canShare: %d\n", canShare+1);
hello('A');
}
output
main -> VAL: 16
main -> canShare: 2
header file -> VAL: 15
header file -> canShare: 1
hello func -> 65
Upvotes: 0
Views: 160
Reputation: 474
static variables at global level are only visible in their own source file whether they got there via an include or were in the main file.
Upvotes: 0
Reputation: 241671
There is a subtle inaccuracy in the interpretation:
A static global variable or a function is "seen" only in the file it's declared in.
It's available only in the translation unit it's declared in. #include
directives literally include the header file into the translation unit, so the TU includes the included header (as you might expect, grammatically).
Upvotes: 3
Reputation: 122363
When you #include
a header, the contents of the header is inserted into the .c file. So in your example, the variable VAL
and the function hello
are in the .c file, it doesn't violate the rule of static
.
To be more precise, identifiers declared as static
has internal linkage, which means they have their scope in the translation unit. When you #include
a header, that's the same translation unit.
Upvotes: 2