2

I've seen some codes like this:

#define A // macro
A void foo(bar); // function declaration

and this:

#define B // macro
class B foo { // class declaration
  bar
};

What's the meaning of using a macro there?

Er...I mean I don't understand the grammar. I haven't seen this before.

In fact, I just find this kind of codes in features2d.hpp in opencv3.1.

class CV_EXPORTS_W BOWImgDescriptorExtractor {
...
CV_WRAP void setVocabulary( const Mat& vocabulary );
...
}

In cvdef.h

#if (defined WIN32 || defined _WIN32 || defined WINCE || defined __CYGWIN__) && defined CVAPI_EXPORTS
#  define CV_EXPORTS __declspec(dllexport)
#elif defined __GNUC__ && __GNUC__ >= 4
#  define CV_EXPORTS __attribute__ ((visibility ("default")))
#else
#  define CV_EXPORTS
#endif

/* special informative macros for wrapper generators */
#define CV_EXPORTS_W CV_EXPORTS
#define CV_WRAP

Here, CV_EXPORTS_W and CV_WRAP are macros. I haven't seen this kind of grammar in C++.

yikouniao
  • 921
  • 1
  • 8
  • 15

2 Answers2

5

Usually such things are a placeholder for compiler or system specific extensions to the language.

For example, if building a program using a windows DLL, to import a symbol the function might be declared

__declspec(dllimport) void foo();

The problem is that the __declspec(dllimport) would typically not work if the code is ported to another system, or built using a compiler that does not support such a non-standard feature.

So, instead, the declaration might be

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

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

IMPORT void foo();

There are a number of occasions, with particular compilers, targets (e.g. a program importing a symbol from a library, or a library being built to export a symbol), and host systems where such a technique might be used.

Peter
  • 35,646
  • 4
  • 32
  • 74
2

Er...I mean I don't understand the grammar.

It is a pre-processor macro definition. The first one defines macro by the name A and second by the name of B. Once those are defined, all occurrences of the identifier A and B are replaced with an empty string by the preprocessor. It is also possible for the preprocessor to test whether a macro is defined and conditionally produce code, using #ifdef.

What's the meaning of using a macro there?

The name of the macros are not helpful, so it's impossible to tell.

As for __declspec(dllexport) see my answer to another question. It is an implementation defined specifier for dynamic linking used in msvc compiler. __attribute__ is a specifier for implementation defined behaviour in the GNU compiler. The macro is used to select the correct specifier depending on the target compiler.

Community
  • 1
  • 1
eerorika
  • 232,697
  • 12
  • 197
  • 326