extern 關鍵字和宏定義,C 和 C-- 混合開發

extern "C"

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 語言中,必須取消 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_EXPORT

聲明一個導入函數,表明當前函數是從其他 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

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/4NOgOyjhhZYv4WU3_uiN5g