爲什麼混用 C C++ 需要 #ifdef __cplusplus extern "C"

關於這個問題,我知道的知識有:C++ 標準庫包含了所有的 C 標準庫1

所以我覺得 C++ 用 C 裏面的東西應該沒啥大問題,因此也一直不太理解爲什麼需要下面這段代碼

#ifdef __cplusplus
extern "C" {
#endif
...
#ifdef __cplusplus
}
#endif

昨天聽同學聊天說到這個,被 diss 一番。於是今天下決心到網上搜了搜,發現好像是 C++ 和 C 的語法有些地方會衝突。因此如果要混合 C C++ 代碼時,編譯器生成的目標文件會有差異

While C and C++ maintain a large degree of source compatibility, the object files their respective compilers produce can have important differences that manifest themselves when intermixing C and C++ code.

但是這些差異會導致啥後果還是不大知道(無能落淚)

詳細資料參考:

  1. 爲什麼 C++ 能夠源碼級兼容C語言? - 馮東的回答
  2. Compatibility of C and C++
  3. C++ FQA: mixing C and C++

至於 #ifdef __cplusplus 如何工作的,可以看 Combining C++ and C - how does #ifdef __cplusplus work?


  1. C++ Standard Library and C standard library ↩︎

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章