用cmake构建gtk程序

情况说明

先前已经在windows下基于GDI实现了一个简陋的imshow。考虑跨平台,也考虑万一某天M$不让我们用盗版系统了,还是需要实现一个Linux下的imshow。

GTK相当于GDI在Linux下的一个替代。我用的ubuntu16.04,unity桌面,因此估计是系统自带了GTK。

官方GTK文档的tutorial给出了一个能运行的例子,不过构建工具用的非常raw的gcc和pkg-config,未免过于刀耕火种。用CMake改造一下也是可以的。这里简单记录。

放码过来

依赖

  • pkg-config
sudo apt install pkg-config
  • cmake

手动下载解压配置最新的cmake,例如3.14

目录结构

CMakeLists.txt

src/main.c

build/

代码

CMakeLists.txt

试了下直接find_package(GTK)不行。需要搭配pkg-config,cmake已经对此做出封装。

cmake_minimum_required (VERSION 3.14)
project (hello-gtk)

find_package (PkgConfig REQUIRED)
pkg_check_modules (GTK3 REQUIRED gtk+-3.0)

include_directories (${GTK3_INCLUDE_DIRS})
link_directories (${GTK3_LIBRARY_DIRS})

add_executable (gtk-test src/main.c)

#add_definitions (${GTK3_CFLAGS_OTHER})
message(STATUS "----- ${GTK3_CFLAGS_OTHER}")
# -pthread

target_link_libraries (gtk-test ${GTK3_LIBRARIES})

main.c

#include <gtk/gtk.h>

static void activate(GtkApplication* app, gpointer user_data)
{
    GtkWidget *window;

    window = gtk_application_window_new (app);
    gtk_window_set_title (GTK_WINDOW (window), "Window");
    gtk_window_set_default_size (GTK_WINDOW (window), 200, 200);
    gtk_widget_show_all (window);
}

int main(int argc, char** argv)
{
    GtkApplication *app;
    int status;

    app = gtk_application_new ("org.gtk.example", G_APPLICATION_FLAGS_NONE);
    g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);
    status = g_application_run (G_APPLICATION (app), argc, argv);
    g_object_unref (app);

    return status;
}

cmake ..执行结果:

-- The C compiler identification is GNU 5.4.0
-- The CXX compiler identification is GNU 5.4.0
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Found PkgConfig: /usr/bin/pkg-config (found version "0.29.1") 
-- Checking for module 'gtk+-3.0'
--   Found gtk+-3.0, version 3.18.9
-- ----- -pthread
-- Configuring done
-- Generating done
-- Build files have been written to: /home/chris/dev/libfc/gtk/build

make之后运行得到窗口:

用cmake构建gtk程序

reference
How do I link gtk library more easily with cmake in windows?

上一篇:交叉编译


下一篇:KC705E增强版基于FMC接口的 Kintex-7 XC7K325T PCIeX8 接口卡