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

Name Mangling และ extern "C" ใน C++


ใน C++ ใช้ function overloading สร้างฟังก์ชันชื่อเดียวกันหลายฟังก์ชัน แตกต่างกันที่ชนิดและจำนวนอาร์กิวเมนต์ return type ไม่นับ C++ แยกแยะ overloaded functions ใน object code อย่างไร?

ใน object code จะเปลี่ยนชื่อโดยเพิ่มข้อมูลอาร์กิวเมนต์ เทคนิคนี้เรียกว่า Name Mangling C++ ไม่มีมาตรฐานสำหรับ name mangling compiler ต่างๆ ใช้เทคนิคต่างกัน

ตัวอย่าง Name Mangling

int func(int x) { return x*x; } double func(double x) { return x*x; } void my_function(void) { int x = func(2); double y = func(2.58); }

บาง compiler จะเปลี่ยนเป็น:

ตัวอย่าง

int __func_i(int x) { return x*x; } double __func_d(double x) { return x*x; } void __my_function_v(void) { int x = __func_i(2); double y = __func_d(2.58); }

C ไร้ function overloading ต้องมั่นใจว่าชื่อ symbol ไม่เปลี่ยนตอน link C code ใน C++ โค้ด C++ ต่อไปจะ error:

ตัวอย่าง

int printf(const char *format,...); main() { printf("Hello World"); }

ผลลัพธ์

undefined reference to `printf(char const*, ...)' ld returned 1 exit status

ปัญหาเกิดเพราะชื่อ printf() ถูกเปลี่ยนโดย compiler หา definition ไม่เจอ แก้ด้วย extern "C" ใน C++ โค้ดใน block นี้ compiler รับประกันว่า function name ไม่ถูก mangle

ตัวอย่าง

extern "C" { int printf(const char *format,...); } main() { printf("Hello World"); }

ผลลัพธ์

Hello World

หมายเหตุ: บล็อกโค้ดเหล่านี้อาจให้ผลลัพธ์ต่างกันใน compiler ต่างๆ