C++中的extern“C”
发布日期:2021-05-09 07:19:34 浏览次数:10 分类:博客文章

本文共 1452 字,大约阅读时间需要 4 分钟。

首先引入extern"C"的官方解释

extern "C" is meant to be recognized by a C++ compiler and to notify the compiler that the noted function is (or to be) compiled in C style.

Take an example, if you are working on a C++ project but it also deals with some existing C functions/libraries.
You want to wrap them in a C++ module or compile them with other C++ objects without any C++ compiler errors, then you would declare the C function prototypes in an extern "C" block to notify the compiler that they would be compiled along with other C++ functions into one module.
翻译为汉语,大致为以下内容:
extern“ C”旨在由C ++编译器识别,并通知编译器所注明的功能已(或将要)以C样式进行编译。
例如,如果您正在从事C ++项目,但它也处理一些现有的C函数/库。
您希望将它们包装在C ++模块中或与其他C ++对象一起编译而没有任何C ++编译器错误,然后在extern“ C”块中声明C函数原型以通知编译器它们将与其他C ++一起编译功能集成到一个模块中
通俗的来说,就是:
将C++里的代码用C语言的规则去编译。
来看官方给出的实例:

my_C_CPP_Header.h://这是一个头文件(第三方库)#ifndef MY_C_CPP_HEADER#define MY_C_CPP_HEADER/*check if the compiler is of C++*/检查编译器是否为C++#ifdef __cplusplusextern "C" {int myOtherCfunc(int arg1, int arg2); /* a C function */}#endifvoid myCppFunction1(); /* C++ function */void myCppFunction2(); /* C++ function *//*check if the compiler is of C++ */#ifdef __cplusplus}#endif#endif

我个人理解是:

首先检查是不是在C++编译器中执行C的代码,如果在C++编译器中而且是C的函数那么久将extern"C"里的代码编译为C的代码。
经过上述操作现在就可以将三个函数编译为一个模块。
exturn"C"有两种书写方式
第一种

exturn "C"void func1();exturn "C"void func2();//exturn 后面的代码执行为C,以分号为结束

第二种

exturn "C"{void func1();void func2();}//直接利用括号,那么exturn"C"的作用范围就是括号里的代码

原文摘自

以上个人理解内容如有错误,还请指点纠正

上一篇:C++内联函数
下一篇:实用网站持续更新

发表评论

最新留言

能坚持,总会有不一样的收获!
[***.219.124.196]2025年04月14日 08时03分55秒