undefined refernce


H

hon123456

Dear all,
I followed the following example to create a executable file
link with dll. All goes fine but when it come to last command, gcc -o
hello.exe hello.o message.dll
This error message appeared :gcc -o hello.exe hello.o message.dll
hello.o:hello.cpp:(.text+0x2b): undefined reference to
`_imp___Z5hellov'

Please Help.

I'm now going to describe a standard "Hello world" implementation. The
code is in three files: hello.c, dll.h and dll.c. The code is listed
and explained below:

hello.c

#include <stdio.h>
#include "dll.h"

int main () {
hello();
return 0;
}


Hello.c is a standard hello world C program except that the hello()
function is going to be dynamically linked. The only special thing
here is the inclusion of dll.h.

dll.h

#ifdef BUILD_DLL
/* DLL export */
#define EXPORT __declspec(dllexport)
#else
/* EXE import */
#define EXPORT __declspec(dllimport)
#endif

EXPORT void hello(void);
DLL.h is where most of the magic happens. It begins with checking the
BUILD_DLL macro. We manually set this macro when building so that the
macro EXPORT is set to __declspec(dllexport), so that gcc can build
the dll. When the OS calls up the dll from the executable, BUILD_DLL
is not set and therefore EXPORT is set to __declspec(dllimport) which
is a nice set of macro routines to expose our function to the calling
scope.

Note that __declspec(dllexport) and __declspec(dllimport) are mingw
macros to faciliate DLL creation. They are mapped to their equivalent
WinAPI headers.

dll.c

#include
#include "dll.h"

EXPORT void hello(void) {
printf ("Hello\n");
}
This is the actual code of the hello world routine. There should be
nothing special here.

Compiling and Linking the files
DLL creation used to be a tiresome process. Recent advances in gcc and
mingw engines have meant that it takes only four steps now to create a
dll. They are:

1.Creating the object code for hello.c

gcc -c hello.c
2.Creating the object code for the dll
gcc -c -DBUILD_DLL dll.c
Notice the use of the -D param by which we set the macro BUILD_DLL. It
is used for setting export to __declspec(dllexport) so that
compilation can take place.

3.Creating the dll
gcc -shared -o message.dll dll.o -Wl,--out-implib,libmessage.a

4.Creating the executable
gcc -o hello.exe hello.o message.dll
The fourth step is actually a bit of gcc magick. The actual step is
something like this:

gcc -o hello.exe hello.o -L./ -lmessage
The -L param means that the linker checks the ./ path for imports
-lmessage (or -l message) means to search for the message linker name.
It extracts this from message.dll

Once you've finished these steps, run the program!

C:\>hello
Hello!
 
Ad

Advertisements


Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top