【问题标题】:NOT sharing all classes with shared library不与共享库共享所有课程
【发布时间】:2010-12-10 22:03:00
【问题描述】:

虽然微软的 win32 编译器使用 __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
{
    ...
}

【问题讨论】:

    标签: c++ linux gcc g++ shared-libraries


    【解决方案1】:

    如果一个类不应该可用,它就不应该在公共标头中。分享用户不能使用的东西的声明有什么意义?

    【讨论】:

    • 难道连仅在 cpp 文件中定义的符号都仍然可以访问吗?我想我可以在我自己的头文件中“模拟”一个声明来访问它们,即使这不是 DLL 的作者的意图。
    • @Matthieu:在这种情况下,你搞砸了,而不是图书馆作者。在一家经营良好的商店里,有能力的人,不能和不应该有什么区别?
    • @David Thornley:您评论中的第二句话是宝石!
    【解决方案2】:

    这在 GCC 4.0 及更高版本中是可能的。 GCC 人员考虑了这种可见性。在 GCC wiki 上有一个很好的 article 关于这个主题。这是那篇文章的一个sn-p:

    #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);
    };
    

    【讨论】:

    • BUILDING_DLL 有必要吗?你需要在哪种情况下禁止这个宏?对静态库没有影响...?
    猜你喜欢
    • 1970-01-01
    • 2016-08-07
    • 1970-01-01
    • 2012-07-29
    • 2013-11-27
    • 1970-01-01
    • 1970-01-01
    • 2016-01-02
    • 2014-03-02
    相关资源
    最近更新 更多