Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

Static Functions (ฟังก์ชัน Static) ใน C

ฟังก์ชัน 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

Static Functions ใน Header Files

ไม่แนะนำ - หาก Header ถูก Include หลายที่ จะได้หลาย Copies ของฟังก์ชัน (Wasted Space)

// header.h - ไม่ดี
static void helper() { ... }

// file1.c #include "header.h" → ได้ helper() copy 1
// file2.c #include "header.h" → ได้ helper() copy 2

ทางเลือกใน C++: Anonymous Namespace

// C++ Style (Preferred over static functions in .cpp)
namespace {
    void internalHelper() { ... }  // Internal Linkage
}

สรุป

  • ใช้ static กับฟังก์ชันใน .c files เพื่อจำกัด Scope ให้อยู่ในไฟล์นั้นๆ
  • ช่วย Encapsulation และป้องกัน Name Collision
  • ไม่ควรวางใน Header Files
  • ใน C++ ใช้ Anonymous Namespace แทน
ประโยชน์คำอธิบาย
Encapsulationซ่อน Implementation Details ไม่ให้ไฟล์อื่นเข้าถึง
Namespace Pollutionป้องกันชื่อฟังก์ชันชนกันระหว่างไฟล์ (Name Collision)
OptimizationCompiler อาจ Inline หรือ Optimize ได้ดีกว่า (รู้ว่าไม่ถูกเรียกภายนอก)
Securityลด Attack Surface - ฟังก์ชันภายในไม่ถูกเรียกจากภายนอก