【c++】小项目cJSON研读

cJSON 研读

github地址:https://github.com/DaveGamble/cJSON

cJSON.h

宏定义部分

#ifdef __cplusplus 
extern "C"
{
   
	// 正常声明段
}
#endif

c的编译器和c++的编译器在生成函数名时处理有所不同,为了确保c编译后的函数,在链接时能正确被c++的编译器识别,.extern"C"是使C++能够调用C写作的库文件的一个手段。

#if !defined(__WINDOWS__) && (defined(WIN32) || defined(WIN64) || defined(_MSC_VER) || defined(_WIN32))
#define __WINDOWS__
#endif

#ifdef __WINDOWS__
....
....
#else /* !__WINDOWS__  不是WINDOWS环境的情况*/
#define CJSON_CDECL
#define CJSON_STDCALL

确保是在WINDOWS环境下

#define CJSON_CDECL __cdecl    // 函数调用约定
#define CJSON_STDCALL __stdcall

举例:
    int _stdcall function(int a, int b); 
表示使用函数的调用方式为 stdcall
这意味着
(1)参数从右向左依次压入堆栈.2)由被调用函数自己来恢复堆栈,称为自动清栈。
(3)函数名自动加前导下划线,后面紧跟着一个@,其后紧跟着参数的大小

详细见:C/C++ 函数调用约定(__cdecl、__stdcall、__fastcall)_c++静态函数 _cdecl-CSDN博客

#if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) && !defined(CJSON_EXPORT_SYMBOLS)
#define CJSON_EXPORT_SYMBOLS
#endif

#if defined(CJSON_HIDE_SYMBOLS)
#define CJSON_PUBLIC(type)   type CJSON_STDCALL
#elif defined(CJSON_EXPORT_SYMBOLS)
#define CJSON_PUBLIC(type)   __declspec(dllexport) type CJSON_STDCALL
#elif defined(CJSON_IMPORT_SYMBOLS)
#define CJSON_PUBLIC(type)   __declspec(dllimport) type CJSON_STDCALL
#endif

#if (defined(__GNUC__) || defined(__SUNPRO_CC) || defined (__SUNPRO_C)) && defined(CJSON_API_VISIBILITY)
#define CJSON_PUBLIC(type)   __attribute__((visibility("default"))) type
#else
#define CJSON_PUBLIC(type) type
#endif
#endif

这里干的事情可以结合后面函数定义来理解,例如以下输出版本信息的函数。

CJSON_PUBLIC(const char*) cJSON_Version(void);

CJSON_PUBLIC(const char*)对应于#define CJSON_PUBLIC(type),其中const char* 作为type 传入,如果在CJSON_EXPORT_SYMBOLS模式下(另外两种模式:CJSON_HIDE_SYMBOLS、CJSON_IMPORT_SYMBOLS)

则CJSON_PUBLIC(type)被定义为 __declspec(dllexport) type CJSON_STDCALL。

因此此函数可以翻译为 __declspec(dllexport) const char* CJSON_STDCALL cJSON_Version(void);

关于 __declspec关键字可以看 C++导入导出符号(dllimport/dllexport) - 知乎 (zhihu.com)

其他的几个#define CJSON_PUBLIC(type)同理。

/* project version */
#define CJSON_VERSION_MAJOR 1
#define CJSON_VERSION_MINOR 7
#define CJSON_VERSION_PATCH 17

#include 

/* cJSON Types: */
#define cJSON_Invalid (0)
#define cJSON_False  (1 << 0)
#define cJSON_True   (1 << 1)
#define cJSON_NULL   (1 << 2)
#define cJSON_Number (1 << 3)
#define cJSON_String 

你可能感兴趣的:(c++各项目学习,c++,开发语言)