-
-
Notifications
You must be signed in to change notification settings - Fork 0
Exporting shared library elements
Here we will discuss how to export classes/functions from shared library (Karma engine library) so that they may be used by the application.
On Windows platform, DLLs are used for dynamically linking shared libraries. The idea is to use __declspec(dllexport) keyword which informs the compiler to set the following class/function for export. This essentially creates .lib file containing the information related to exported elements.
Generally macros like LIBRARYNAME_API are used to export the elements. In Karma we define KARMA_API as follows (Karma code)
#ifdef KR_WINDOWS_PLATFORM
#ifdef KR_BUILD_DLL
#define KARMA_API __declspec(dllexport)
#else
#define KARMA_API __declspec(dllimport)
#endif
#else
#error Supports Windows only!
#endifThen we can define a class (or function) in the following manner (Karma code)
class KARMA_API Application
{
public:
Application();
~Application();
void Run();
};Now the class Application can be imported by another program (outside of DLL), by including relevant header, as shown here.
For Linux we have shared object (.so) files which are analogous to DLLs. We modify the code to make KARMA_API accessible in Linux as follows
#ifdef KR_WINDOWS_PLATFORM
#ifdef KR_BUILD_DLL
#define KARMA_API __declspec(dllexport)
#else
#define KARMA_API __declspec(dllimport)
#endif
#elif defined KR_LINUX_PLATFORM
#ifdef KR_BUILD_SO
#define KARMA_API __attribute__((visibility("default")))
#else
#define KARMA_API
#endif
#else
#error Unsupported Platform detected!
#endifMake sure to define macros KR_LINUX_PLATFORM and KR_BUILD_SO for the projects appropriately. Premake can be used for this purposed (see here).
Also we have added linkoptions { '-Wl,-rpath=\\$$ORIGIN' } here so that the Application may look for the .so file in the same directory.
This entire issue is smoothly handled by CMake in a development platform invariant way by setting the variable like so
option(BUILD_SHARED_LIBS "Build shared libraries" ON)
However Windows seems defiant enough and it seems that extra
set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON)
is needed to do the work of __declspec(dllexport) for exporting symbols.