Absolute beginners guide to compiling dll’s with g++
Using the gcc / g++ compiler is really great for a few reasons. One of these reasons is its open source, so it cost you no money!!! What a great price.
A second reason is that it works across various operating systems. We use it equally on both Linux and Windows (any guess which one we prefer???).
We’re going to give you a quick, dirty guide to compiling and linking a simple dll using the g++ compiler and writing in C++. Please note that this really is a basic example (did you think we were kidding when we called it the ABSOLUTE beginners guide???).
Right, firstly we need three files for this example:
- testdll.H
- testdll.cpp
- testprog.cpp
The code in the dll header file should look as follows:
/*——————————————————————————————
testdll.H
——————————————————————————————-*/
#include <stdio>
class SomeClass
{
public:int hello();
};
The next file, testdll.cpp looks like this:
/*——————————————————————————————
testdll.cpp
——————————————————————————————-*/
#include “testdll.H”int SomeClass::hello()
{
printf (“Hello World!\n”);
return 0;
}
and then lastly, the main program page looks like this:
/*——————————————————————————————
testprog.cpp
——————————————————————————————-*/
#include “testdll.H”
using namespace std;int main ()
{
SomeClass c;
c.hello ();
}
Now to do the compiling. We are assuming that all of these files are in the same directory and that you are compiling from the command line in Linux using a standard terminal or from MinGW (also open source) using Windows.
- g++ -c testdll.cpp
- This results in a file called testdll.o
- ar -rv libtestdll.a testdll.o
- Create a shared library called libtestdll.a from the object we just created
- g++ -o testprog testprog.cpp -L ./ -ltestdll
If all went well you should now be able to run the program using ./testprog
This exact program has been tested on both Windows (XP) and Linux (Mandriva 2009.1).
NOTE:
- The .cpp and .H files need a carriage return at the end of the file. So after the last line of code, hit enter, then save.
- In step 2 of the compilation process you created a library called libtestdll.a. In step 3 you used that lib with the -ltestdll option. The option to link is -l and the library name is testdll. You do not call the library libtestdll in this option because the compiler assumes the lib part… Make sense?
for a far more in depth look at the gcc compiler, take a look at Phoxis blog.
Well, that’s it for our not-so-earth-shattering, earth shattering tutorial. We hope it helps. If you have any questions about this, or if you require any custom software work, give us a call, we’re always happy to help!
John
Tags: C++, compilers, g++, gcc