在C++中,extern "C"
用于指示编译器按照C语言的链接规范来处理被声明的代码。这在需要与C语言代码进行互操作时非常有用,因为C++的名称修饰(name mangling)与C语言不同。
使用场景
- C++调用C代码:当你在C++代码中调用C语言的函数时,使用
extern "C"
来确保正确的链接。 - C代码调用C++代码:当你希望C语言代码调用C++函数时,也需要使用
extern "C"
来确保正确的链接。
示例
1. C++调用C代码
假设你有一个C语言的头文件和实现文件:
C语言头文件(example.h):
#ifndef EXAMPLE_H
#define EXAMPLE_H
#ifdef __cplusplus
extern "C" {
#endif
void c_function();
#ifdef __cplusplus
}
#endif
#endif // EXAMPLE_H
C语言实现文件(example.c):
#include "example.h"
#include <stdio.h>
void c_function() {
printf("This is a C function.\n");
}
C++代码(main.cpp):
#include <iostream>
extern "C" {
#include "example.h"
}
int main() {
c_function();
return 0;
}
2. C代码调用C++代码
假设你有一个C++的头文件和实现文件:
C++头文件(example.hpp):
#ifndef EXAMPLE_HPP
#define EXAMPLE_HPP
extern "C" {
void cpp_function();
}
#endif // EXAMPLE_HPP
C++实现文件(example.cpp):
#include "example.hpp"
#include <iostream>
void cpp_function() {
std::cout << "This is a C++ function." << std::endl;
}
C代码(main.c):
#include "example.hpp"
int main() {
cpp_function();
return 0;
}
解释
- C语言头文件(example.h):使用
extern "C"
来确保在C++编译器中正确处理C语言的函数声明。 - C++头文件(example.hpp):使用
extern "C"
来确保在C语言编译器中正确处理C++的函数声明。 - C++代码(main.cpp):通过
extern "C"
包含C语言的头文件,以确保正确的链接。 - C代码(main.c):直接包含C++的头文件,因为头文件中已经使用了
extern "C"
。
总结
extern "C"
在C++中用于指示编译器按照C语言的链接规范来处理被声明的代码。这在需要与C语言代码进行互操作时非常有用。通过使用extern "C"
,你可以确保C++代码和C代码之间的正确链接。希望这些示例能帮助你更好地理解和使用extern "C"
。