Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use GLib functions?

Tags:

c

gtk

glib

While programming in C and GTK+, why is it "better" to use g_strdup_printf, g_free, g_strcmp0 etc... and fellow GLib functions?

like image 490
Zenet Avatar asked Feb 10 '10 20:02

Zenet


People also ask

What is the purpose of GLib?

GLib implements functions that provide threads, thread programming and related facilities such as primitive variable access, mutexes, asynchronous queues, secure memory pools, message passing and logging, hook functions (callback registering) and timers.

Is GLib the same as glibc?

glibc is a core C runtime library. It provides things like printf(3) and fopen(3) . glib is an object-based event loop and utility library written in C. gnulib is a library that provides an adapter from the POSIX API to the native API.

What is Libglib?

GLib is the low-level core library that forms the basis for projects such as GTK and GNOME. It provides data structure handling for C, portability wrappers, and interfaces for such runtime functionality as an event loop, threads, dynamic loading, and an object system.


2 Answers

In general, GLib's purpose is a utility and portability library. Those in itself are reasons to consider using it.

The specific functions you mention all offer something extra on top of their C standard library variants:

  • g_strdup_printf is like sprintf, but actually allocates the buffer for you and saves you the guesswork of how large the buffer should be. (The return value should be g_free'd.)
  • g_free is like free, but checks for a NULL-pointer.
  • g_strcmp0 is like strcmp, but treats a NULL-pointer like an empty string, and thus sorts it in front.
like image 139
Stéphan Kochen Avatar answered Sep 20 '22 23:09

Stéphan Kochen


For consistent behavior in multiple operating systems. It's a portability thing.

In some other unix environments other than Linux, or if your program is compiled on windows, some of those functions may not exist or behave differently on the target operating system.

Using the glib versions ensure consistent behavior.

like image 21
Bob Avatar answered Sep 21 '22 23:09

Bob