不与共享库共享所有类

Ian*_*han 5 c++ linux gcc g++ shared-libraries

像Win32一样丑陋的Microsoft编译器是使用__declspec宏,它确实具有明确关于你想要导出什么的优点.

将相同的代码移动到Linux gnu/gcc系统现在意味着导出所有类!(?)

这是真的吗?

有没有办法在gcc下的共享库中导出类?

#ifndef WIN32
#define __IMPEXP__
#else
#undef __IMPEXP__
#ifdef __BUILDING_PULSETRACKER__
#define __IMPEXP__ __declspec(dllexport)
#else
#define __IMPEXP__ __declspec(dllimport)
#endif // __BUILDING_PULSETRACKER__
#endif // _WIN32

class __IMPEXP__ MyClass
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*Dan 13

这在GCC 4.0及更高版本中是可行的.GCC人员考虑了这种可见性.GCC wiki上有一篇关于这个主题的好文章.以下是该文章的摘录:

#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
    #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
 public:
   Person(int _c) : c(_c) { }
   static void foo(int a);
};
Run Code Online (Sandbox Code Playgroud)