C++ 中函数或类之前的宏是什么?

yik*_*iao 2 c++

我见过一些像这样的代码\xef\xbc\x9a

\n\n
#define A // macro\nA void foo(bar); // function declaration\n
Run Code Online (Sandbox Code Playgroud)\n\n

和这个:

\n\n
#define B // macro\nclass B foo { // class declaration\n  bar\n};\n
Run Code Online (Sandbox Code Playgroud)\n\n

那里使用宏的意义是什么?

\n\n

呃...我的意思是我不懂语法。我以前没见过这个。

\n\n

事实上,我只是在features2d.hppopencv3.1中找到了这种代码。

\n\n
class CV_EXPORTS_W BOWImgDescriptorExtractor {\n...\nCV_WRAP void setVocabulary( const Mat& vocabulary );\n...\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

在cvdef.h中

\n\n
#if (defined WIN32 || defined _WIN32 || defined WINCE || defined __CYGWIN__) && defined CVAPI_EXPORTS\n#  define CV_EXPORTS __declspec(dllexport)\n#elif defined __GNUC__ && __GNUC__ >= 4\n#  define CV_EXPORTS __attribute__ ((visibility ("default")))\n#else\n#  define CV_EXPORTS\n#endif\n\n/* special informative macros for wrapper generators */\n#define CV_EXPORTS_W CV_EXPORTS\n#define CV_WRAP\n
Run Code Online (Sandbox Code Playgroud)\n\n

这里,CV_EXPORTS_W和CV_WRAP是宏。我在C++中没见过这种语法。

\n

Pet*_*ter 5

通常这些东西是编译器或系统特定语言扩展的占位符。

例如,如果使用 Windows DLL 构建程序,要导入符号,可以声明该函数

__declspec(dllimport) void foo();
Run Code Online (Sandbox Code Playgroud)

问题是,__declspec(dllimport)如果代码被移植到另一个系统,或者使用不支持此类非标准功能的编译器构建,则通常无法工作。

因此,相反,声明可能是

#ifdef _WIN32    /*  or some macros specific to a compiler targeting windows */

#define IMPORT __declspec(dllimport)
#else
#define IMPORT
#endif

IMPORT void foo();
Run Code Online (Sandbox Code Playgroud)

在许多情况下,特定的编译器、目标(例如,从库导入符号的程序,或为导出符号而构建的库)和主机系统可能会使用这种技术。