__declspec(dllimport) 的真正含义是什么?

2021-12-09 00:00:00 dll qt visual-c++ c++ declspec

我看到的Qt源代码是这样的:

I saw the Qt source code like this:

class Q_CORE_EXPORT QBasicAtomicInt
{
public:
...
};

Q_CORE_EXPORT 宏定义如下:

define Q_DECL_IMPORT __declspec(dllimport)

那么 __declspec(dllimport) 到底是什么意思?

So what does __declspec(dllimport) really mean?

推荐答案

__declspec 是 Microsoft 特定的属性,允许您指定存储类信息.
(Nitpicker's Corner:但是,许多其他编译器供应商(例如 GCC)现在支持此语言扩展,以便与针对 Microsoft 编译器编写的已安装代码库兼容.有些甚至提供额外的存储类属??性.)

可以指定的两个存储类属性是 dllimportdllexport.这些向编译器表明函数或对象是从 DLL 导入或导出(分别).

Two of those storage-class attributes that can be specified are dllimport and dllexport. These indicate to the compiler that a function or object is imported or exported (respectively) from a DLL.

更具体地说,它们定义了 DLL 到客户端的接口,而无需模块定义 (.DEF) 文件.大多数人发现使用这些语言扩展比创建 DEF 文件要容易得多.

More specifically, they define the DLL's interface to the client without requiring a module-definition (.DEF) file. Most people find it much easier to use these language extensions than to create DEF files.

出于显而易见的原因,__declspec(dllimport)__declspec(dllexport) 通常是相互配对的.您使用 dllexport 将符号标记为从 DLL 导出,然后使用 dllimport 将该导出的符号导入另一个文件.

For obvious reasons, __declspec(dllimport) and __declspec(dllexport) are generally paired with one another. You use dllexport to mark a symbol as exported from a DLL, and you use dllimport to import that exported symbol in another file.

因此,并且因为在编译 DLL 时和在使用 DLL 接口的客户端代码中通常使用相同的头文件,定义一个在编译时自动解析为适当属性说明符的宏是一种常见模式-时间.例如:

Because of this, and because the same header file is generally used both when compiling the DLL and in client code that consumes the DLL's interface, it is a common pattern to define a macro that automatically resolves to the appropriate attribute specifier at compile-time. For example:

#if COMPILING_DLL
    #define DLLEXPORT __declspec(dllexport)
#else
    #define DLLEXPORT __declspec(dllimport)
#endif

然后用DLLEXPORT标记所有应该导出的符号.

And then marking all of the symbols that should be exported with DLLEXPORT.

据推测,这就是 Q_CORE_EXPORT 宏所做的,解析为 Q_DECL_IMPORTQ_DECL_EXPORT.

Presumably, that is what the Q_CORE_EXPORT macro does, resolving to either Q_DECL_IMPORT or Q_DECL_EXPORT.

相关文章