Creating a portable library to run on both linux and windows

前端 未结 5 1720
野趣味
野趣味 2020-12-23 18:20
gcc (GCC) 4.7.2

Hello,

I am creating a shared library that will compile on linux and a dll that will compile on windows using the same sour

5条回答
  •  离开以前
    2020-12-23 18:30

    This is a typical way to export a DLL API for Windows and still support Linux:

    #ifdef __cplusplus
    extern "C" {
    #endif
    
    #ifdef _WIN32
    #  ifdef MODULE_API_EXPORTS
    #    define MODULE_API __declspec(dllexport)
    #  else
    #    define MODULE_API __declspec(dllimport)
    #  endif
    #else
    #  define MODULE_API
    #endif
    
    MODULE_API int module_init();
    
    #ifdef __cplusplus
    }
    #endif
    

    In the DLL source:

    #define MODULE_API_EXPORTS
    #include "module.h"
    
    MODULE_API int module_init()
    {
        /* do something useful */
        return 0;
    }
    

    Your application source is correct.

    Using the above model, on Windows the DLL will export the API while the application will import it. If not on Win32, the __declspec decoration is removed.

    Since the header wraps the entire interface in extern "C", using the EXTERN_C macro on each interface is not required. extern "C" is used to tell the linker to use C linkage instead of C++. C linkage is standard across compilers, whereas C++ is not, limiting the use of a DLL to application built with the same compiler.

    There is no need to integrate the return type into the API macro.

提交回复
热议问题