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然后根据需要链接不同的目标文件。
阅读完成 · 觉得有帮助?