【问题标题】:Correct usage of __declspec(dllimport)正确使用 __declspec(dllimport)
【发布时间】:2011-12-19 00:00:07
【问题描述】:

我想构建 2 个 dll,我们称它们为 FooBar。我想让BarFoo 导入一些类。

Foo.h:

#ifdef EXPORT
#define DECL __declspec(dllexport)
#else
#define DECL __declspec(dllimport)
#endif

class DECL Foo {
public:
        Foo();
        void bar();
};

Bar.cpp:

#include "bar.h"
void bar(){
        Foo f;
        f.bar();
}

要构建 Foo.dll,我会这样做

g++ -DEXPORT -c Foo.cpp -o Foo.o
g++ -shared Foo.o -o Foo.dll

这会在 Foo.o 中产生以下引用:

$ nm Foo.o
00000000 b .bss
00000000 d .data
00000000 i .drectve
00000000 t .text
0000000c T __ZN3Foo3barEv
00000006 T __ZN3FooC1Ev
00000000 T __ZN3FooC2Ev

现在,当我想构建 Bar.dll 时,我会这样做

$ g++ -shared Bar.cpp -o Bar.dll
/tmp/ccr8F57C.o:Bar.cpp:(.text+0xd): undefined reference to `__imp___ZN3FooC1Ev'
/tmp/ccr8F57C.o:Bar.cpp:(.text+0x1a): undefined reference to `__imp___ZN3Foo3barEv'

如果我尝试在未定义 EXPORT 的情况下构建 Foo.cpp(以便宏 DECL 计算为 __declspec(dllimport),我会得到以下信息:

$ g++ -c Foo.cpp
Foo.cpp:3: warning: function 'Foo::Foo()' is defined after prior declaration as dllimport: attribute ignored
Foo.cpp: In constructor `Foo::Foo()':
Foo.cpp:3: warning: function 'Foo::Foo()' is defined after prior declaration as dllimport: attribute ignored
Foo.cpp: In member function `void Foo::bar()':
Foo.cpp:7: warning: function 'void Foo::bar()' is defined after prior declaration as dllimport: attribute ignored

这是有道理的,因为声明为 dllimport 的函数不能被定义。

我应该如何在Bar 中引用Foo

【问题讨论】:

  • 不是 __declspec(dllexport) 用于 MSVC++ 吗?
  • @SethCarnegie 我正在使用 MinGW
  • 啊,不知道MinGW支持那个。

标签: c++ dll dllimport


【解决方案1】:

当您构建Bar.dll 时,您还需要使用-l 选项链接Foo.lib

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-18
  • 2012-02-10
  • 1970-01-01
  • 2013-03-26
  • 1970-01-01
  • 2013-07-29
  • 2011-06-10
相关资源
最近更新 更多