Writing a shared lib that can be linked under windows (dll) or macos (dylib)
I have created a repository with an example approach here
VS, Windows and dlls
VS in Windows needs declarations like __declspec(dllexport)
and __declspec(dllimport).
The generate appropriate declarations is to use cmake’s generate_export_header
like this:
include(GenerateExportHeader)
generate_export_header(mylib)
This way declaration of MYLIB_EXPORT
is placed in the mylib_EXPORT.h file and can be used in a header like this:
MYLIB_EXPORT void myfunctionApi();
Templates
Templates are not instantiated in dynamic libraries. To deal with it, if you know what type you are going to use, you can use explicit template instantiation, i.e.
template class MYLIB_EXPORT myclass<int>;
template class MYLIB_EXPORT myclass<double>;
With templates, one usually writes declaration in a .h file and definition (implementation) in .hxx file. To make implementation visible from .h file, one can #include "mylib.hxx"
at the end of .h file. In libraries we do not want to share the implementation, so one can export .h files in the include folder and surround the include .hxx
with guard
#ifdef mylib_EXPORTS
#include "mylib.hxx"
#endif
The compiler knows how to deal with mylib_EXPORTS
thanks to setting the add_library
to SHARED
. You can see it during verbose build.
References
https://anteru.net/blog/2008/11/19/318/index.html