Your _get_type() function is not G_GNUC_CONST

It’s not uncommon in GNOME to annotate the _get_type() function declaration of a GObject with G_GNUC_CONST. Like so:

GType ephy_download_get_type (void) G_GNUC_CONST;

What does this do? It expands to __attribute__((__const__)) if the compiler is GCC (or a compiler that pretends to be GCC, like Clang); otherwise, it expands to nothing. What does that attribute do? I could point you at the GCC documentation, but GLib’s documentation is simpler: “Declaring a function as const enables better optimization of calls to the function. A const function doesn’t examine any values except its parameters, and has no effects except its return value.” That’s really all there is to it. What’s important to keep in mind is that if your function doesn’t meet the preconditions for the attribute, the compiler is free to make optimizations that break your code.

Since G_DEFINE_TYPE defines our _get_type() functions for us, it can be easy to forget what’s actually in there. Here’s the canonical example, from the GObject documentation:

GType maman_bar_get_type (void)
  static GType type = 0;
  if (type == 0) {
    const GTypeInfo info = {
      /* You fill this structure. */
    type = g_type_register_static (G_TYPE_OBJECT,
                                   &info, 0);
  return type;

The first thing you should notice is that it examines a value (type) that’s not a parameter. Next, you should notice that it has an effect other than its return value: it modifies type, and then registers with the type system. Obviously G_GNUC_CONST is not appropriate here. Fix your headers. Update: If you scroll down to the first comment below, Giovanni recommends using G_GNUC_CONST anyway and also g_type_ensure as a workaround for if you don’t use the return value of the function.

Note that the new, highly-recommendable G_DECLARE_FINAL_TYPE and G_DECLARE_DERIVABLE_TYPE macros declare this function for you, so future code should be immune to this problem. Update: Those macros do not use G_GNUC_CONST, but maybe they will in the future? Who can say!

P.S. I’m not the one who noticed this — it was brought up by somebody (Christian?) at the Boston Summit last year — but I don’t think anybody has blogged about it yet. Update: It was pointed out in the comments that this was noticed long ago. Here’s a GLib bug report about breakage in Glade, and my colleague Andy Wingo has a blog post about a GStreamer bug this caused.