【C++】外部接口封装关键字extern

发布时间:2026/10/30 1:59:11
【C++】外部接口封装关键字extern

extern "C"的作用

在 C++ 中,extern "C"主要用于解决 C++ 和 C 语言混合编程时的链接问题。C++ 编译后函数名会进行重整(name mangling),而 C 语言不会。extern "C"可以让 C++ 编译器按照 C 语言的方式来编译和链接函数,这样 C++ 代码就能调用 C 语言编写的函数,反之亦然。

示例一:C++ 调用 C 函数

  • 首先创建一个 C 语言文件example.c:
// example.c #include <stdio.h> // C语言函数 void printMessage(const char* msg) { printf("C function: %s\n", msg); }
  • 然后在 C++ 文件main.cpp中调用这个 C 函数:
// main.cpp extern "C" { // 声明C函数 void printMessage(const char* msg); } int main() { printMessage("Hello from C++ calling C function"); return 0; }
  • 在上述示例中,在 C++ 代码中通过extern "C"声明了 C 函数printMessage,这样 C++ 编译器就知道按照 C 语言的链接规则去寻找这个函数,从而可以成功调用。

示例二:在 C++ 头文件中使用extern "C"以支持 C 和 C++ 包含

  • 创建一个头文件common.h:
// common.h #ifndef COMMON_H #define COMMON_H #ifdef __cplusplus extern "C" { #endif // 函数声明 void sharedFunction(); #ifdef __cplusplus } #endif #endif
  • 接着创建 C++ 实现文件cpp_impl.cpp:
// cpp_impl.cpp #include "common.h" #include <iostream> void sharedFunction() { std::cout << "This is from C++ implementation\n"; }
  • 再创建 C 语言实现文件c_impl.c:
// c_impl.c #include "common.h" #include <stdio.h> void sharedFunction() { printf("This is from C implementation\n"); }
  • 这样,无论是 C 还是 C++ 代码都可以包含common.h头文件。在 C++ 代码中,extern "C"确保函数声明按照 C 语言的规则处理,而在 C 代码中,#ifdef __cplusplus条件编译确保 C 代码不会受到 C++ 特定语法(如extern "C")的影响。

在编译时,对于示例一,需要分别编译example.c和main.cpp并链接。例如,使用 GCC 编译器可以这样编译:

gcc -c example.c g++ -c main.cpp g++ main.o example.o -o main

对于示例二,在编译 C++ 实现时可以用g++ -c cpp_impl.cpp,编译 C 实现时用gcc -c c_impl.c,然后根据需要链接不同的目标文件。