Visual C++ >> Console
extern "C"
在C++語言中,由於每一個副程式會被編譯器修飾,導致在二進制連結時,會有不相容的問題,爲了解決這個問題,可以在每個副程式前面,使用extern "C"關鍵字,強制該副程式使用C語言的修飾方式,如果檔名本身就是以*.c爲副檔名,則不需使用這個關鍵字,因爲編譯器會自動使用C語言的方式作修飾。
原始程式(test.cpp)
extern "C" void test1(void) { } extern "C" void test2(int x) { } extern "C" int test3(int x) { return 0; }
編譯後的Object File
Dump of file test.obj File Type: COFF OBJECT RELOCATIONS #4 Symbol Symbol Offset Type Applied To Index Name -------- ---------------- ----------------- -------- ------ 00000020 SECREL 00000000 E _test1 00000024 SECTION 0000 E _test1 RELOCATIONS #6 Symbol Symbol Offset Type Applied To Index Name -------- ---------------- ----------------- -------- ------ 00000020 SECREL 00000000 1B _test2 00000024 SECTION 0000 1B _test2 RELOCATIONS #8 Symbol Symbol Offset Type Applied To Index Name -------- ---------------- ----------------- -------- ------ 00000020 SECREL 00000000 28 _test3 00000024 SECTION 0000 28 _test3
原始程式(test.cpp)
void test1(void) { } void test2(int x) { } int test3(int x) { return 0; }
編譯後的Object File
Dump of file test.obj File Type: COFF OBJECT RELOCATIONS #4 Symbol Symbol Offset Type Applied To Index Name -------- ---------------- ----------------- -------- ------ 00000020 SECREL 00000000 E ?test1@@YAXXZ (void __cdecl test1(void)) 00000024 SECTION 0000 E ?test1@@YAXXZ (void __cdecl test1(void)) RELOCATIONS #6 Symbol Symbol Offset Type Applied To Index Name -------- ---------------- ----------------- -------- ------ 00000020 SECREL 00000000 1B ?test2@@YAXH@Z (void __cdecl test2(int)) 00000024 SECTION 0000 1B ?test2@@YAXH@Z (void __cdecl test2(int)) RELOCATIONS #8 Symbol Symbol Offset Type Applied To Index Name -------- ---------------- ----------------- -------- ------ 00000020 SECREL 00000000 28 ?test3@@YAHH@Z (int __cdecl test3(int)) 00000024 SECTION 0000 28 ?test3@@YAHH@Z (int __cdecl test3(int))
使用者可以看到編譯後的Object File,編譯器對於C語言和C++語言有不同的修飾做法。