javagrendel
javagrendel

Reputation: 91

Correct usage of __declspec(dllimport)

I want to build 2 dlls, lets call them Foo and Bar. I want Bar to import some class from Foo.

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();
}

To build Foo.dll, I do

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

This produces the following references in 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

Now, when I want to build Bar.dll, I do

$ 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'

If I try to build Foo.cpp with EXPORT not defined (so that the macro DECL evaluates to __declspec(dllimport), I get the following:

$ 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

which does make sense, since a function declared dllimport can't then be defined.

How am I supposed to reference Foo in Bar?

Upvotes: 2

Views: 2704

Answers (1)

parapura rajkumar
parapura rajkumar

Reputation: 24413

When you build Bar.dll you also need to link against Foo.lib with -l option

Upvotes: 3

Related Questions