5

As ugly as win32 Microsoft compiler is by using the __declspec macro, it does have the advantage of being explicit about what you want to export or not.

Moving the same code onto a Linux gnu/gcc system now means all classes are exported!(?)

Is this really true?

Is there a way to NOT export a class within a shared library under 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
{
    ...
}
Ian Vaughan
  • 20,211
  • 13
  • 59
  • 79

2 Answers2

13

This is possible in GCC 4.0 and later. The GCC folks consider this visibility. There is a good article on the GCC wiki about the subject. Here is a snippet from that article:

#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);
};
Dan
  • 3,485
  • 2
  • 21
  • 25
  • Is the `BUILDING_DLL` necessary? It which case do you need to inhibited this macro? It has no impact on static lib...? – Sandburg May 29 '19 at 13:32
1

If a class shouldn't be available, it shouldn't be in a public header. What is the point of sharing declarations of things the user can't use?

unwind
  • 391,730
  • 64
  • 469
  • 606
  • Aren't even symbols defined only in cpp files still accessible though ? I think I could 'emulate' a declaration within my own header file to access them even if it wasn't the intent of the author of the DLL. – Matthieu M. Oct 28 '09 at 16:38
  • 1
    @Matthieu: In which case you're screwing up, not the library author. In a well-run shop with competent people, what's the difference between can't and shouldn't? – David Thornley Oct 28 '09 at 16:49
  • @David Thornley: the second sentence in your comment is a gem! – just somebody Feb 03 '10 at 15:43
  • @unwind: Misses the point. The question isn't about headers; it's about link entry points in the .so/.dll, which are significantly large when C++ member declarations that should have been private implementation details leak into a compiled binary. – Robin Davies Mar 13 '22 at 21:51