craigp | 6 Sep 12:48
Favicon

globals best-practices (avoiding multiple definitions)

Hi -

I'm trying to understand the best practice for handling globals (within a namespace), and in particular,
avoiding multiple definitions (whether multiple "private" copies or collisions causing a linker error).

For namespace globals, if I do something like this (in a header file):

  namespace log_categories
  {
    static log_t server(log_t::category("http.server.server"));
  }

I'd guess that each translation unit (TU) would get its own copy of log_categories::server (or maybe some
compilers give a multiple-definition link error, while others would just make multiple private
copies?). OTOH, if I only declared the variable and put the definition in a c++ file, there would only be a
single copy.

For class static members, you cannot initialize the members "in-line" (unless it's an integral constant).

One interesting "work-around" I saw in asio/error.hpp was this:

namespace boost { ...

  static const boost::system::error_category& system_category
    = boost::asio::error::get_system_category();
...

This way, there might be multiple copies but they will all be references to the same underlying object.

For the case of class template static members, I found this example in complex.hpp:
(Continue reading)


Gmane