GLib 是 GTK+ 和 GNOME 的核心基礎庫,提供跨平台的數據結構(鏈表、哈希表、樹等)、工具函數(字符串、文件、線程、主循環)、對象系統(GObject)等。最初為 GTK+ 內部模塊,後獨立發布,支持 Linux/Unix、Windows、macOS 等。
cd /usr/ports/devel/glib20
make install clean
sudo apt-get install libglib2.0-dev
pacman -S mingw-w64-x86_64-glib2
使用 pkg-config 自動獲取編譯標誌:
gcc `pkg-config --cflags --libs glib-2.0 gthread-2.0` main.c -o myapp
GLib 定義固定寬度類型,消除平台差異:
gint/guint、glong/gulong、gint64/guint64gchar、guchar、gfloat、gdoublegboolean(TRUE/FALSE)gpointer(void* 別名)#include <glib.h>
int main(int argc, char *argv[]) {
GRand *rand = g_rand_new(); // 創建隨機數生成器
GTimer *timer = g_timer_new(); // 創建計時器
// 生成 20 個 1-100 隨機數
for (int n = 0; n < 20; ++n)
g_print("%d\t", g_rand_int_range(rand, 1, 100));
g_print("\n");
g_rand_free(rand);
// 計時 3000 萬次累加
g_timer_start(timer);
gint x = 0;
for (int i = 0; i < 10000; ++i)
for (int j = 0; j < 3000; ++j)
++x;
g_timer_stop(timer);
g_print("%ld\tall: %.2f seconds used!\n", x, g_timer_elapsed(timer, NULL));
g_timer_destroy(timer);
return 0;
}
96 24 52 87 52 16 62 17 78 62 76 6 33 53 87 3 40 69 20 33
30000000 all: 0.08 seconds used!
| 功能 | 函數 |
|---|---|
| 隨機數 | g_rand_new(), g_rand_int_range(), g_rand_free() |
| 計時器 | g_timer_new(), g_timer_start(), g_timer_stop(), g_timer_elapsed(), g_timer_destroy() |
| 輸出 | g_print()(類 printf,跨平台) |
GLib 為 C 語言補齊了「標準庫不足」的短板,是構建跨平台、可維護、高性能應用的利器。掌握其類型系統與核心模塊,事半功倍。