scopeには、時間と空間の範囲があることを意識するとわかりやすい。
scope_b.hをincludeしている。
#include <stdio.h> #include "scope_b.h"
int outer_int = 100;
/* file local function */
static void get_name() { printf("get_name\n"); }
/* declare global function */
void get_address() { printf("address:%d", outer_int);
}
scope_b.cで実装したグローバル変数、グローバル関数を外部(extern)に公開するために記述する。
scope_b.h
#ifndef __SCOPE_B_H__
#define ___SCOPE_B_H__
#endif
extern int out_int;
extern void get_address();
scope_b.hをincludeしているのでouter_int, get_addressを利用できる状態になる。
main関数内でローカル変数にstatic修飾子を記述している。これによりスタック上に
メモリ領域が確保されるのではなく、プログラム領域に確保される。つまり永続的に
データの確保が出来る。
#include <stdio.h>
#include "scope_b.h"
/* global variable */
int g_hoge = 0;
/* file local variable */
static int st_hoge = 0;
/* global function */
void get_name() { printf("get name\n"); }
/* file local function */
static void get_age() { printf("100\n");
}
int main(int argc, char *argv[]) { static int st_local = 100;
printf("%d\n", st_local); get_address();
return 0;
}