c++ 中的__declspec關鍵字

        其實__declspec關鍵字是Microsoft c++中專用的關鍵字,它配合着一些屬性可以對標準C++進行擴充。這些屬性有:align、allocate、
deprecated、 dllexport、dllimport、 naked、noinline、noreturn、nothrow、novtable、selectany、thread、property和uuid。
我們這裏主要講述的是函數從動態庫中導入與導出的問題,置於其他的作用請大家自查,我不過多簡述:
       _declspec(dllimport)   是說這個函數是從別的DLL導入的,供自己用的
       _declspec(dllexport)   是說這個函數要從本DLL導出的,是供別人用的
如果下在C++動態函數C導出的定義,只要項目屬性-->C++-->Preprocessor中輸入TEST_EXPORTS就可以導出函數,如果沒有定義是導入
#if (defined WIN32 || defined _WIN32) && defined TEST_EXPORTS
#	define TEST_API_EXPORTS __declspec(dllexport)
#elif defined __GNUC__ && __GNUC__ >= 4
#	define TEST_API_EXPORTS __attribute__ ((visibility ("default")))
#else
#	define TEST_API_EXPORTS
#endif


#ifndef TEST_EXTERN_C
#	ifdef __cplusplus
#		define TEST_EXTERN_C extern "C"
#	else
#		define TEST_EXTERN_C
#	endif
#endif

#if defined WIN32 || defined _WIN32
#	define TEST_CDECL		__cdecl
#	define TEST_STDCALL	__stdcall
#else
#	define TEST_CDECL
#	define TEST_STDCALL
#endif

#ifndef TEST_API
#  define TEST_API(rettype) TEST_EXTERN_C TEST_API_EXPORTS rettype TEST_CDECL
#endif

#ifndef TEST_IMPL
#  define TEST_IMPL TEST_EXTERN_C
#endif

參考例子:
TEST_API(bool) Test_DLL(const char* str); ///聲明函數,頭文件中
TEST_IMPL bool Test_DLL(const char* str){ return true} //實現函數,源文件中
發佈了109 篇原創文章 · 獲贊 29 · 訪問量 45萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章