为了在C文件中使用C++代码,我读到了我们可以做的extern "C" { (where the c++ code goes here)},但是当我尝试使用cout打印出来时,我不断收到错误,因为它无法识别库.我想我对extern"C"如何允许你在C中使用C++代码感到困惑.
该extern "C"构造是一种特定于C++的语法,没有C编译器会理解它.
这就是为什么你几乎总是看到它与一些配对条件编译像
#ifdef __cplusplus
extern "C" {
#endif
...
#ifdef __cplusplus
}
#endif
Run Code Online (Sandbox Code Playgroud)
什么extern "C" 不是简单地抑制名称重整含义是,在一个C++源文件所定义的符号可以在C程序中使用.
这允许您拥有一个具有混合C和C++源的项目,并且C源可以调用已定义为的C++函数extern "C".
非常简单,愚蠢的例子只是为了说明这一点:
假设我们有一个C源文件,用C编译器编译:
#include <stdio.h>
void foo(void); // Declare function prototype, so it can be called
int main(void)
{
printf("Calling foo...\n");
foo();
printf("Done\n");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
然后我们有一个foo函数的C++源文件:
#include <iostream>
extern "C" void foo()
{
std::cout << "Hello from foo\n";
}
Run Code Online (Sandbox Code Playgroud)
C源文件使用C编译器编译,C++源文件使用C++编译器编译.然后将两个目标文件链接在一起以形成可执行程序.因为foo定义为extern "C"它的符号名称在目标文件中没有被破坏,并且链接器可以从C编译器创建的目标文件中解析引用.
它也适用于另一个方向.因为C中的符号没有被破坏,所以C++编译器需要知道这一点,并且通过extern "C"使用如上所示的条件编译通常在头文件中声明C符号来完成.如果extern "C"没有使用,C++编译器会认为符号是C++符号,并且当链接器找不到损坏的符号时,会破坏导致链接器问题的名称.
同样愚蠢的例子:首先是一个C++源文件
#include <iostream>
extern "C" void bar(); // Declare function prototype as an unmangled symbol
int main()
{
std::cout << "Calling bar...\n";
bar();
}
Run Code Online (Sandbox Code Playgroud)
然后是C源文件
#include <stdio.h>
void bar(void)
{
printf("Inside bar\n");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2568 次 |
| 最近记录: |