正确使用__declspec(dllimport)

时间:2011-12-19 00:00:08

标签: c++ dll dllimport

我想构建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的函数。

我应该如何在Foo中引用Bar

1 个答案:

答案 0 :(得分:3)

构建Bar.dll时,您还需要使用Foo.lib选项<{1}}与-l进行关联