Extern storage class = ตัวแปร global ใช้ร่วมได้หลายไฟล์ (.c)
คุณสมบัติ
- Keyword:
extern - Scope: ทั้งโปรแกรม (ทุกไฟล์ที่ include)
- Default value: 0
- ประกาศใน header file แล้ว define ใน .c ไฟล์หนึ่ง
อัลกอริทึม
START
Step 1: ประกาศ extern variable
Step 2: ประกาศ local variable a=3
Step 3: Print a (local)
Step 4: เรียกฟังก์ชัน fun()
Step 5: ใน fun() print a (extern)
โปรแกรมที่ 1: Extern ในไฟล์เดียว
extern int a = 5; // global
main() {
int a = 3; // local ใน main
printf("%d\n", a); // 3
fun();
}
fun() {
printf("%d\n", a); // 5 (extern)
}
ผลลัพธ์
3
5
โปรแกรมที่ 2: แยกไฟล์ (External.h + externstorage.c)
External.h
extern int a = 14;
extern int b = 8;
externstorage.c
#include <stdio.h>
#include "External.h"
int main() {
int sub = a - b;
printf("%d - %d = %d\n", a, b, sub);
return 0;
}
ผลลัพธ์
14 - 8 = 6