萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C 與 C++ 混合編程:extern "C" 跨語言呼叫完整指南

核心問題:名稱修飾

C++ 編譯器為支援**多載、命名空間、樣板**,會對函數名進行 **Name Mangling** (如 ?Func@@YAXH@Z)。C 編譯器**不修飾** (僅 _Func 或 Func)。跨語言呼叫必須**關閉 C++ 修飾**,強制使用 C 連結約定。

場景一:C 庫提供給 C/C++ 共用 (最常見)

標準頭檔模式

// myclib.h — 同時被 .c 和 .cpp 包含
#ifndef MYCLIB_H
#define MYCLIB_H

#ifdef __cplusplus
extern "C" {  // 告訴 C++ 編譯器:下列符號用 C 連結
#endif

// 介面宣告
void MyCFunc(int param);
int  AnotherCFunc(const char* str);

#ifdef __cplusplus
}
#endif
#endif
  • #ifdef __cplusplus:僅在 C++ 編譯單元展開 extern "C",C 編譯器忽略。
  • **同一份頭檔**即可被 C 與 C++ 專案包含,零維護成本。

C 端實作

// myclib.c
#include "myclib.h"
#include 

void MyCFunc(int param) {
    printf("C func called with %d\n", param);
}

int AnotherCFunc(const char* str) {
    return strlen(str);
}

C++ 端呼叫

// main.cpp
#include "myclib.h"
int main() {
    MyCFunc(42);
    int len = AnotherCFunc("Hello");
    return 0;
}

場景二:C++ 庫提供給 C 呼叫

C 無法直接呼叫 C++ 函數 (修飾名、this 指標、例外、多載)。**必須建立 C 風格包裝層**。

C++ 實作檔

// cpp_lib.cpp
#include "cpp_lib.h" // C++ 類別定義
#include 

class Calculator {
public:
    int Add(int a, int b) { return a + b; }
    std::string Greet(const char* name) { return "Hello " + std::string(name); }
};

// ---- C 包裝層 ----
extern "C" {
    // 不透明指標隱藏 C++ 類別細節
    typedef struct CalculatorOpaque* CalculatorHandle;

    CalculatorHandle Calculator_Create() {
        return reinterpret_cast(new Calculator());
    }

    void Calculator_Destroy(CalculatorHandle handle) {
        delete reinterpret_cast(handle);
    }

    int Calculator_Add(CalculatorHandle handle, int a, int b) {
        return reinterpret_cast(handle)->Add(a, b);
    }

    // 字串回傳:呼叫端負責 free
    char* Calculator_Greet(CalculatorHandle handle, const char* name) {
        std::string s = reinterpret_cast(handle)->Greet(name);
        char* ret = (char*)malloc(s.size() + 1);
        strcpy(ret, s.c_str());
        return ret;
    }

    void Calculator_FreeString(char* str) {
        free(str);
    }
}

C 端頭檔

// cpp_lib.h — 純 C 介面
#ifndef CPP_LIB_H
#define CPP_LIB_H

#ifdef __cplusplus
extern "C" {
#endif

typedef struct CalculatorOpaque* CalculatorHandle;

CalculatorHandle Calculator_Create(void);
void Calculator_Destroy(CalculatorHandle);
int Calculator_Add(CalculatorHandle, int, int);
char* Calculator_Greet(CalculatorHandle, const char*);
void Calculator_FreeString(char*);

#ifdef __cplusplus
}
#endif
#endif

C 端呼叫範例

// main.c
#include "cpp_lib.h"
#include 

int main() {
    CalculatorHandle h = Calculator_Create();
    printf("Add: %d\n", Calculator_Add(h, 3, 5));
    char* greeting = Calculator_Greet(h, "World");
    printf("%s\n", greeting);
    Calculator_FreeString(greeting);
    Calculator_Destroy(h);
    return 0;
}

場景三:C++ 專案直接包含 C 頭檔 (無標準頭檔時)

// 只有 legacy_c.h (無 extern "C")
extern "C" {
    #include "legacy_c.h"
}
// 所有 legacy_c.h 內的函數皆以 C 連結視之

進階議題與避坑指南

議題解決方案
C++ 例外跨越 C 邊界包裝層 **catch 所有例外** 轉為錯誤碼返回,絕不讓例外傳播到 C 碼
C++ 類別物件跨邊界使用**不透明指標** (Opaque Pointer / Pimpl),C 端只見 void* 或前向宣告結構體
C++ 多載函數包裝層為每個多載版本提供**不同名稱**的 C 函數 (如 Func_Int, Func_Double)
全域物件建構/解構順序避免跨 DLL 邊界的全域 C++ 物件,改用函數內部 static (Meyers Singleton)
STL 容器跨邊界**嚴禁**。轉為 C 風格陣列/緩衝區 + 長度,或序列化 (JSON/Protobuf)
編譯器 ABI 不相容同專案同編譯器版本;跨 DLL 邊界**純 C 介面**最安全

建置系統整合

  • CMake:target_link_libraries(cpp_exe PRIVATE c_lib),CMake 自動處理語言混合。
  • Visual Studio:C 專案設為「編譯為 C 程式碼 (/TC)」,C++ 專案「/TP」;DLL 匯出用 __declspec(dllexport/import) 配合 extern "C"。
  • GCC/Clang:gcc -c myc.c、g++ -c main.cpp、g++ main.o myc.o -o app。

結語

extern "C" 是 C/C++ 混合編程的**唯一標準橋樑**。核心原則:**C++ 端包裝、C 介面暴露、不透明指標隱藏實作、例外不出邊界、記憶體誰分配誰釋放**。遵循此模式,即可無縫整合 C 庫生態與 C++ 現代抽象能力。

copyright © 萬盛學電腦網 all rights reserved