This morning I have the interest in exploring c deeper, and wrote some c form how-to files, and added annotations on each try-out conclusions:
1. main.c
#include <stdio.h>
#include "_ref.h"
static int sub()
{
staticintb = 0;
for (inti = 0; i < 5; i++)
{
b++;
}
returnb;
}
extern float sub1() // empty body float type return returns random space by default;
{
}
/*
remember to assign value to variable declaration;
static, extern does not work for direct referencing like "#include "_ref.c"", but works for "#include "_ref.h"" by running gcc cstringtest.c _ref.h _ref.c
*/
int main() // int return value is not mandatory to be specified, non-void by default int a=sub() returns 1;
{
inta = sub(); // sub() returns 5 when 1st called;
printf("a:%d\n", a);
intaa = sub(); // call sub() once again, the static value is accumulated to 10;
printf("aa:%d\n", aa);
floata1 = sub1();
printf("a1:%f\n", a1);
doublea2;
printf("a2:%f\n", a2);
inta3;
printf("a3:%d\n", a3);
floata4;
printf("a4:%f\n", a4);
{
constinta1 = 0;
// extern int ab; // extern is used to ref global variables defined in other files; like public to open public visit; if b does not exist, linker will throw error;
printf("a1:%d\n", a1);
printf("ab:%d\n", ab); // ab is static in header file, it is 0 here; static is used to hide from other files by being in header;
printf("ac:%d\n", ac); // ac does not need extern;
externint ad; // extern to use ad declared in _ref.c; or else ad is not declared in _ref.h;
ad = 58;
printf("ad:%d\n", ad);
}
p();
}
2. _ref.h
#ifndef REF_H
#define REF_H
int p(void);
static int ab;
int ac;
#endif
3. _ref.c
#include "_ref.h"
#include <stdio.h>
static int ab = 56;
int ac = 65;
extern int ad = 57;
int p(void)
{
printf("pp");
}
4. run
gcc main.c _ref.h _ref.c