extern与__declspec(dllimport)的区别

  1. "extern" is for statically linked libraries?
  2. "__declspec(dllimport)" is for DLL (dynamically linked libraries)?
  3. both do actually the same job for their respective type of linking?
  4. you need to use both when you use import libraries (small .lib files that help linking with dll)?

1 Answer

up vote 28 down vote accepted

extern means that the entity has external linkage, i.e. is visible outside its translation unit (C or CPP file). The implication of this is that a corresponding symbol will be placed in the object file, and it will hence also be visible if this object file is made part of a static library. However, extern does not by itself imply that the symbol will also be visible once the object file is made part of a DLL.

__declspec(dllexport) means that the symbol should be exported from a DLL (if it is indeed made part of a DLL). It is used when compiling the code that goes into the DLL.

__declspec(dllimport) means that the symbol will be imported from a DLL. It is used when compiling the code that uses the DLL.

Because the same header file is usually used both when compiling the DLL itself as well as the client code that will use the DLL, it is customary to define a macro that resolves to __declspec(dllexport)when compiling the DLL and __declspec(dllimport) when compiling its client, like so:

#if COMPILING_THE_DLL
    #define DLLEXTERN __declspec(dllexport)
#else
    #define DLLEXTERN __declspec(dllimport)
#endif

To answer your specific questions:

  1. Yes, extern alone is sufficient for static libraries.
  2. Yes -- and the declaration also needs an extern (see explanation here).
  3. Not quite -- see above.
  4. You don't strictly need the extern with a __declspec(dllimport) (see explanation linked to above), but since you'll usually be using the same header file, you'll already have the extern in there because it's needed when compiling the DLL.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值