开发者

Why do C++ class definitions on Windows often have a macro token after 'class'?

开发者 https://www.devze.com 2022-12-13 06:59 出处:网络
I am trying to understand an open source project, where I came across the following class declaration:

I am trying to understand an open source project, where I came across the following class declaration:

class STATE_API AttributeSubject : public AttributeGroup, public Subject
{
public:
    AttributeSubject(const char *);
    virtual ~AttributeSubject开发者_开发技巧();
    virtual void SelectAll() = 0;
    virtual const std::string TypeName() const; 
    virtual void Notify();
    virtual AttributeSubject *CreateCompatible(const std::string &) const;
    virtual AttributeSubject *NewInstance(bool copy) const { return 0; };

    virtual bool VarChangeRequiresReset(void) { return false; };
};

What does STATE_API before the class name AttributeSubject signify? Is it some sort of macro?


It's probably a typedef to __declspec(dllimport) or __declspec(dllexport) and is used inside DLLs on windows platform to export classes.

Neil is right, it's a macro.

It usually looks like this:

#ifdef INDSIDE_DLL
    #define STATE_API __declspec(dllexport)
#else
    #define STATE_API __declsped(dllimport)
#endif

You define INSIDE_DLL only in your dll and export all the classes declared with STATE_API macro.


It's a macro. What it expands to depends on your platform - it is cannot be part of standard C++ (unless it expands to nothing).


Is this the source code of a DLL project ?

If so, then STATE_API must be a preprocessor macro, enabling you to use the header in which this class is declared in both the library project and the application using the library.

  • in the library project, STATE_API would be defined to __declspec(dllexport)
  • in the project using the library, STATE_API would be defined to __declspec(dllimport)

This is usually achieved with something like this :

#ifdef USRDLL
#define STATE_API __declspec(dllexport)
#else
#define STATE_API __declspec(dllimport)
#endif

USRDLL being defined in the project options of the DLL.


It is a macro:

As a user of the class it is not that important.
It is some platform specific macro that is being used to help (probably) the compiler perform some operation.

As the designer of the class then you are trying to do somthing platform specific to the class and you have already done the research on what it expands into and what that expansion means.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号