Until now, I've only ever compiled .exe applications. I've written a set of utilities in a .cpp and .hpp file that I'd like to share with several other projects and I would like to make the sharing as professional-looking as possible.
I'd rather not add the .cpp file to each project, therefore I think the .dll or .lib compilation options are what I am looking for.
I compiled as a .DLL, added the .hpp file to another project and added the DLL to the bin. However I get Linker errors when I try and access classes from my DLL.
I haven't used __declspec(dllexport) anywhere because I don't have any pure functions that I want to share. Instead I have the following:
- Namespaces
- Classes
- Objects of the Classes (defined in the cpp file and declared with the extern keyword in the hpp file)
- Operator overloading functions for my classes
I think I need __declspec(dllexport), but do I have to add it to every class/namespace/private class function/overloader/object or can I just add it to the namespace that contains all of these things?
I like the SFML libraries and so I am trying to copy their examples, but I don't see them use __declspec(dllexport) anywhere. Do I need to add this to my cpp file instead of my header that defines everything?
A link to a tutorial on this would be appreciated as I have no idea what I'm doing.
The header should contain declarations for functions and classes and should be able to export when building the DLL and import when building another application that implicitly links with the DLL. Eg;
In Dll.h
1 2 3 4 5 6 7 8 9 10 11 12
#ifndef MYDLL
#define MYDLL __declspec(dllimport)
#endif
namespace MyDll
{
// whole class is imported or exported
class MYDLL ImportedExportedClass
{
int myfunc1();
};
}
In Dll.cpp
1 2 3 4 5 6 7 8
#define MYDLL __declspec(dllexport)
#include "Dll.h"
// no need to import/export the implementation
int MyDll::ImportedExportedClass:myfunc1()
{
....
}
When you build the DLL the linker produces a .lib(if any symbols are exported) and a .dll. If you want another application to implicitly link with your DLL you must include Dll.h, link with the .lib file, and put the .dll in the applications' search path. E.g.,
In main.cpp
1 2 3 4 5 6 7 8 9 10 11
#include <MyDll.h>
#pragma comment(linker, "MyDll.lib")
MyDll::ImportedExportedClass myClass;
int main()
{
int ret = myClass.myfunc1();
....
return 0;
}
By the way, you can use the win32 functions LoadLibrary/Ex and GetProcAddress to explicitly link with a DLL and call its exported functions at runtime.