简单的例子

在开始介绍 gtkmm 之前,我们将以一个尽可能简单的程序开始。这个程序创建一个 200 x 200 像素大小的空窗口。

源代码

File: base.cc (For use with gtkmm 3, not gtkmm 2)

#include <gtkmm.h>

int main(int argc, char *argv[])
{
  Glib::RefPtr<Gtk::Application> app =
    Gtk::Application::create(argc, argv,
      "org.gtkmm.examples.base");

  Gtk::ApplicationWindow window;

  return app->run(window);
}

我们会逐行讲解这个例子

#include <gtkmm.h>

所有的 gtkmm 程序都需要包含一些特定的 gtkmm 头文件;gtkmm.h 包含了所有 gtkmm 的内容。通常来说,这并不是一个好主意,因为它包括了一兆左右的头文件。当然,对于这个简单的程序,这就够了。

The next line:

Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.examples.base");
creates a Gtk::Application object, stored in a RefPtr smartpointer. This is needed in all gtkmm applications. The create() method for this object initializes gtkmm, and checks the arguments passed to your application on the command line, looking for standard options such as -display. It takes these from the argument list, leaving anything it does not recognize for your application to parse or ignore. This ensures that all gtkmm applications accept the same set of standard arguments.

接下来的两行代码创建并显示了一个窗口:

Gtk::Window window;

The last line shows the window and enters the gtkmm main processing loop, which will finish when the window is closed. Your main() function will then return with an appropriate success or error code.

return app->run(window);

将源代码保存到 simple.cc 后,你可以使用 gcc 编译上面的程序:

g++ simple.cc -o simple `pkg-config gtkmm-3.0 --cflags --libs`
注意,你必须将 pkg-config 的调用包含在一对反单引号中。反单引号会导致其内的命令由 shell 执行,并且将命令的输出做为该命令行的一部分来使用。