extern "C"用于解决C与C++混合编程中的链接问题,因C++支持函数重载会进行名称修饰,而C语言不会。通过extern "C"声明,可使C++编译器以C语言的命名和调用约定处理函数,确保符号名一致,实现双向调用。在C++中调用C函数时,需在包含头文件时使用extern "C"包裹声明;为让C调用C++函数,则需在C++函数前加extern "C"并避免使用C++特有特性。常见做法是在头文件中使用#ifdef __cplusplus宏判断,自动兼容两种语言。注意extern "C"不适用于类成员函数或函数重载,且编译时应确保C++文件用g++编译并正确链接。

在C++项目中调用C语言代码,或者让C语言代码使用C++编写的函数时,经常会遇到链接错误。这是因为C++支持函数重载,会对函数名进行名称修饰(name mangling),而C语言不会。为了解决这个问题,C++提供了 extern "C" 机制,用来告诉编译器以C语言的方式处理函数声明和链接。
my_c_func.h:
#ifndef MY_C_FUNC_H #define MY_C_FUNC_H void hello_from_c(void); #endif
my_c_func.c:
#include <stdio.h>
#include "my_c_func.h"
void hello_from_c(void) {
    printf("Hello from C!\n");
}
main.cpp:
立即学习“C语言免费学习笔记(深入)”;
extern "C" {
#include "my_c_func.h"
}
int main() {
    hello_from_c();
    return 0;
}
修改 my_c_func.h:
#ifndef MY_C_FUNC_H
#define MY_C_FUNC_H
#ifdef __cplusplus
extern "C" {
#endif
void hello_from_c(void);
#ifdef __cplusplus
}
#endif
#endif
my_cpp_func.cpp:
extern "C" void hello_from_cpp(void) {
    // 只能使用C可调用的内容
    printf("Hello from C++!\n");
}
main.c(C语言主程序):
#include <stdio.h>
// 声明外部函数
extern void hello_from_cpp(void);
int main() {
    hello_from_cpp();
    return 0;
}
gcc -c main.c g++ -c my_cpp_func.cpp g++ main.o my_cpp_func.o -o program
基本上就这些。只要在混合编程时注意函数声明方式和编译链接流程,extern "C" 能很好地解决C与C++之间的互操作问题。
以上就是C++如何使用extern "C"与C语言代码交互_C++ extern "C"使用方法的详细内容,更多请关注php中文网其它相关文章!
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号