extern是C/C++语言中表明函数和全局变量作用范围的关键字,该关键字告诉编译器,其声明的函数和全局变量可以在本模块或其他模块中使用。与extern对应的关键字是static,被该关键字修饰的函数和全局变量只能在本模块中使用。
在C++中引入C语言中的函数和变量,在包含C语言头文件时,需要进行如下处理:
extern "C" {
#include "xxx.h"
}
cat.h:
int sum(int a, int b);
int mul(int a, int b);
cat.c:
int sum(int a, int b) {
return a + b;
}
int mul(int a, int b) {
return a * b;
}
此时,未使用extern "C"声明,找不到sum函数。
extern "C" {
int sum(int a, int b);
int mul(int a, int b);
}
添加extern "C"声明,才可以正常运行。
然而,根据调用的程序是C语言或C++,还要在头文件中进行增加或删除extern "C",这样是非常不方便的。
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
int sum(int a, int b);
int mul(int a, int b);
#ifdef __cplusplus
}
#endif // __cplusplus
如果是C++程序调用,会包括定义#ifdef __cplusplus,否则不会定义#ifdef __cplusplus。
声明一个导入函数,表明当前函数是从其他DLL导入,省略没有影响,然而加上此声明,编译器会生成更有效的代码。
然而,导出和导入在程序中还要进行更换,比较不方便,因此,这个过程也可以通过宏定义进行简化。
cat.h
#ifdef DLL_EXPORT
#define DLL_API _declspec(dllexport)
#else
#define DLL_API _declspec(dllimport)
#endif // _DLL_EXPORT
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
DLL_API int sum(int a, int b);
#ifdef __cplusplus
}
#endif // __cplusplus
在cat.cpp中写上:#define DLL_EXPORT
来源:
https://www.toutiao.com/article/7210677046518137344/?log_from=78671cb80ede_1684891981685
“IT大咖说”欢迎广大技术人员投稿,投稿邮箱:aliang@itdks.com
IT大咖说 | 关于版权
由“IT大咖说(ID:itdakashuo)”原创的文章,转载时请注明作者、出处及微信公众号。投稿、约稿、转载请加微信:ITDKS10(备注:投稿),茉莉小姐姐会及时与您联系!
感谢您对IT大咖说的热心支持!
相关推荐
推荐文章