Creating a portable library to run on both linux and windows

前端 未结 5 1724
野趣味
野趣味 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:21

    For Linux, gcc without -fvisibility=hidden will make functions exported by default, except for static functions.

    With -fvisibility=hidden, gcc will make no functions exported by default, except that functions decorated by

    __attribute__ ((visibility ("default")))
    

    For Windows, exported functions decorated by

    __attribute__ ((dllexport))
    

    when using the exported functions, they must be decorated by

    __attribute__ ((dllimport))
    

    The macros in your posts

    __declspec(dllexport)
    

    are supported by MSVC.

    So the crossed linux and windows macros are as following:

    #if defined _WIN32 || defined __CYGWIN__ || defined __MINGW32__
      #ifdef BUILDING_DLL
        #ifdef __GNUC__
          #define DLL_PUBLIC __attribute__ ((dllexport))
        #else
          #define DLL_PUBLIC __declspec(dllexport) // Note: actually gcc seems to also supports this syntax.
        #endif
      #else
        #ifdef __GNUC__
          #define DLL_PUBLIC __attribute__ ((dllimport))
        #else
          #define DLL_PUBLIC __declspec(dllimport) // Note: actually gcc seems to also supports this syntax.
        #endif
      #endif
      #define DLL_LOCAL
    #else
      #if __GNUC__ >= 4
        #define DLL_PUBLIC __attribute__ ((visibility ("default")))
        #define DLL_LOCAL  __attribute__ ((visibility ("hidden")))
      #else
        #define DLL_PUBLIC
        #define DLL_LOCAL
      #endif
    #endif
    
    • Make sure that shared object or DLL projects must be compiled with -DBUILDING_DLL.
    • The project that depends on your shared object or DLL must be compiled without -DBUILDING_DLL

    For the more details, please read http://gcc.gnu.org/wiki/Visibility

提交回复
热议问题