gcc: __attribute__ ((weak))

Boris Kolpackov boris at kolpackov.net
Wed Mar 31 17:15:50 CST 2004


Good day,


While playing with glibc I noticed one interesting technique. It is
based on gcc's extension that allows you to declare weak symbols. In
essence it works like this:


extern void weak_f (void) __attribute__ ((weak));

int main ()
{
  if (weak_f)
  {
    weak_f ();
  }
}


When you link such code ld won't complain if weak_f is unresolved. 
Plus you can check at run-time if symbol has been resolved as shown 
above.

Interesting effects can be achieved using this technique. For example
you can make some code thread-safe on-demand. You compile this code
once and depending on kind of application it is used in it automatically
becomes multi-threaded or single-threaded:

#include <pthread.h>

extern "C" int
pthread_create (pthread_t*, 
                const pthread_attr_t*, 
                void* (*)(void*), 
                void*) __attribute__ ((weak));

extern "C" int
pthread_mutex_init (pthread_mutex_t*, 
                    const pthread_mutexattr_t*) __attribute__ ((weak));

extern "C" int
pthread_mutex_lock (pthread_mutex_t*) __attribute__ ((weak));

extern "C" int
pthread_mutex_unlock (pthread_mutex_t*) __attribute__ ((weak));

extern "C" int
pthread_mutex_destroy (pthread_mutex_t*) __attribute__ ((weak));


class foo
{
public:

  foo ()
  {
    if (pthread_create) pthread_mutex_init (&m_, 0);
  }
  
  ~foo ()
  {
    if (pthread_create) pthread_mutex_destroy (&m_);
  }


  bar ()
  {
    if (pthread_create) pthread_mutex_lock (&m_);

    // ...

    if (pthread_create) pthread_mutex_unlock (&m_);
  }

private:
  pthread_mutex_t m_;

  // some other data that mutex protects
};


Now if you link your code with libpthread, foo is automatically 
multi-thread-safe. If you don't then all the calls to mutex API 
are skipped.

This could be especially nice if class foo is in the library that
is used by both kinds of applications.

-boris
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 652 bytes
Desc: Digital signature
Url : http://www.kolpackov.net/pipermail/notes/attachments/20040331/da607ad4/attachment.bin


More information about the notes mailing list