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

คลาสการจัดเก็บ extern ใน C++

ตัวระบุคลาสการจัดเก็บ extern ให้คุณประกาศ objects ที่ไฟล์ต้นทางหลายไฟล์สามารถใช้ร่วมกันได้ การประกาศ extern ทำให้ตัวแปรที่อธิบายสามารถใช้งานได้โดยส่วนที่เหลือของไฟล์ต้นทางปัจจุบัน การประกาศนี้ไม่แทนที่ definition (นิยาม) แต่ใช้เพื่ออธิบายตัวแปรที่ถูกนิยามภายนอก (externally defined)

การประกาศ extern สามารถปรากฏนอกฟังก์ชันหรือที่จุดเริ่มต้นของบล็อกได้ หากการประกาศอธิบายฟังก์ชันหรือปรากฏนอกฟังก์ชันและอธิบาย object ที่มี external linkage คีย์เวิร์ด extern เป็น optional

หากมีการประกาศสำหรับ identifier อยู่แล้วที่ file scope การประกาศ extern เดียวกันที่พบภายในบล็อกจะอ้างอิงถึง object เดียวกันนั้น หากไม่มีการประกาศอื่นสำหรับ identifier นั้นที่ file scope identifier จะมี external linkage

C++ จำกัดการใช้ extern storage class specifier ให้กับชื่อของ objects หรือ functions เท่านั้น การใช้ extern specifier กับการประกาศชนิดข้อมูล (type declarations) เป็นสิ่งผิดกฎหมาย การประกาศ extern ไม่สามารถปรากฏใน class scope ได้

คุณสามารถใช้คีย์เวิร์ด extern เพื่อแชร์ตัวแปรข้ามไฟล์ได้ดังนี้:

file3.h

extern int global_variable;  /* Declaration of the variable */

file1.c

#include "file3.h"  /* Declaration made available here */
#include "prog1.h"  /* Function declarations */
/* Variable defined here */
int global_variable = 37;  /* Definition checked against declaration */
int increment(void) {
    return global_variable++;
}

file2.c

#include "file3.h"
#include "prog1.h"
#include <stdio.h>
void use_it(void) {
    printf("Global variable: %d\n", global_variable++);
}

คำถามต่อไปนี้บน Stack Overflow อธิบายความเป็นจริงของคีย์เวิร์ด extern ได้อย่างครบถ้วน: https://stackoverflow.com/questions/1433204/how-do-i-use-extern-to-share-variables-between-source-files