ฟังก์ชัน Static (Static Function) ใน C คือ ฟังก์ชันที่มี Scope จำกัดอยู่ใน Object File (Translation Unit) เดียวกัน ไม่สามารถเรียกใช้จากไฟล์อื่นได้ ใช้คีย์เวิร์ด static นำหน้าประกาศฟังก์ชัน
ไวยากรณ์
static return_type function_name(parameters) {
// function body
}
ตัวอย่าง: Static Function ในไฟล์เดียว
#include <stdio.h>
// Static Function - เรียกได้เฉพาะในไฟล์นี้
static void staticFunc(void) {
printf("Inside the static function staticFunc()\n");
}
int main() {
staticFunc(); // เรียกได้ เพราะอยู่ในไฟล์เดียวกัน
return 0;
}
ผลลัพธ์
Inside the static function staticFunc()
ตัวอย่าง: Error เมื่อเรียกจากไฟล์อื่น
first_file.c
static void staticFunc(void) {
printf("Inside the static function staticFunc()\n");
}
second_file.c
// extern void staticFunc(void); // Error: Static Function ไม่มี External Linkage
int main() {
staticFunc(); // Linker Error: undefined reference to 'staticFunc'
return 0;
}
ผลลัพธ์ข้อผิดพลาด
undefined reference to 'staticFunc()'
เหตุผล: Internal Linkage
staticให้ฟังก์ชันมี Internal Linkage- Symbol ไม่ถูก Export ไปยัง Symbol Table สำหรับ Linker
- Linker ไม่เห็นฟังก์ชันนี้จาก Object Files อื่น
ประโยชน์ของ Static Functions
| ประโยชน์ | คำอธิบาย |
|---|---|
| Encapsulation | ซ่อน Implementation Details ไม่ให้ไฟล์อื่นเข้าถึง |
| Namespace Pollution | ป้องกันชื่อฟังก์ชันชนกันระหว่างไฟล์ (Name Collision) |
| Optimization | Compiler อาจ Inline หรือ Optimize ได้ดีกว่า (รู้ว่าไม่ถูกเรียกภายนอก) |
| Security | ลด Attack Surface - ฟังก์ชันภายในไม่ถูกเรียกจากภายนอก |