Bernhard Kausler Bernhard Kausler - 6 months ago 61
C Question

What are practical applications of weak linking?

Using special compiler commands a symbol can be declared weak. According to Wikipedia:

a weak symbol is a symbol definition in an object file or dynamic library that may be overridden by other symbol definitions

In what scenarios or for what applications do you need weak symbols? What are typical use cases?


One use of weak linking is implementing the replaceable functions in the C++ standard. Namely:

void *operator new(std::size_t);
void *operator new(std::size_t, std::nothrow_t const &) noexcept;
void *operator new[](std::size_t);
void *operator new[](std::size_t, const std::nothrow_t&) noexcept;
void operator delete(void *) noexcept;
void operator delete(void *, std::nothrow_t const &) noexcept;
void operator delete[](void *) noexcept;
void operator delete[](void *, std::nothrow_t const &) noexcept;

These are functions which must be provided by the implementation, but if a program implements them then the program's implementation replaces or overrides the implementation's version. This is easily implemented via weak linkage.