C++跨平台类库导出宏

// Macros.h
#pragma once

#if defined(__GNUC__)
#define _DEPRECATED_ __attribute__((deprecated))
#define _FORCE_INLINE_ __attribute__((always_inline))
#elif defined(_MSC_VER)
#define _DEPRECATED_
#define _FORCE_INLINE_ __forceinline
#else
#define _DEPRECATED_
#define _FORCE_INLINE_ inline
#endif

/*
  Windows import/export and gnu http://gcc.gnu.org/wiki/Visibility
  macros.
 */
#if defined(_MSC_VER)
    #define DLL_IMPORT __declspec(dllimport)
    #define DLL_EXPORT __declspec(dllexport)
    #define DLL_LOCAL
#elif __GNUC__ >= 4
    #define DLL_IMPORT __attribute__ ((visibility("default")))
    #define DLL_EXPORT __attribute__ ((visibility("default")))
    #define DLL_LOCAL  __attribute__ ((visibility("hidden")))
#else
    #define DLL_IMPORT
    #define DLL_EXPORT
    #define DLL_LOCALs
#endif

// Ignore warnings about import/exports when deriving from std classes.
#ifdef _MSC_VER
  #pragma warning(disable: 4251)
  #pragma warning(disable: 4275)
#endif

// Import/export for windows dll's and visibility for gcc shared libraries.


#ifdef BUILD_SHARED_LIBS   // project is being built around shared libraries
    #ifdef CLASS_EXPORTS   // we are building a shared lib/dll
        #define CLASS_DECL DLL_EXPORT
    #else                  // we are using shared lib/dll
        #define CLASS_DECL DLL_IMPORT
    #endif

    #ifdef FUNC_EXPORTS    // we are building a shared lib/dll
        #define FUNC_DECL DLL_EXPORT
    #else                  // we are using shared lib/dll
        #define FUNC_DECL DLL_IMPORT
    #endif
#else                      // project is being built around static libraries
    #define CLASS_DECL
    #define FUNC_DECL
#endif

Example:

#if defined _WIN32 || defined __CYGWIN__
  #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

extern "C" DLL_PUBLIC void function(int a);
class DLL_PUBLIC SomeClass
{
   int c;
   DLL_LOCAL void privateMethod();  // Only for use within this DSO(Dynamic Shared Object)
public:
   Person(int _c) : c(_c) { }
   static void foo(int a);
};

参考:

  http://gcc.gnu.org/wiki/Visibility

 

posted @ 2022-05-18 10:59  碎银三二两  阅读(286)  评论(0编辑  收藏  举报