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
extern int canShare;in a header, but writingint canShare = 1;in a header treads into implementation-defined, not-strictly-standard behaviour. For more details, see What areexternvariables in C?#include "header.h"directives will include the contents ofheader.hduring compilation, so they are actually part ofmain.ccontents ?#include "header.h"copies the named header into the text of the TU (and any nested headers). That's the job of the C preprocessor; the C compiler proper simply sees the result of all the#includelines being honoured, and macros being expanded, and conditional inclusion of code (#if…#elif…#else…#endif) being managed. There's usually a way to see the preprocessor output. Sometimes you runcppdirectly; with GCC, you can usegcc -Eorgcc -P.