如何在 C 中包含和使用 cairo 图形库?

How to include and use cairo graphics library in C?

我最近从 project website 下载并安装了 C 的 Cairo 图形库。

我尝试使用站点 FAQ 中的给定代码 运行 Cairo 的 hello world 程序。在终端中,我应用了同一页面给出的相同命令来编译它。但是当我试图编译它时,出现了未定义引用的错误。

在终端中,输出为:

 cc -o hello $(pkg-config --cflags --libs cairo) hello.c
 /tmp/cco08jEN.o: In function `main':
 hello.c:(.text+0x1f): undefined reference to `cairo_image_surface_create'
 hello.c:(.text+0x2f): undefined reference to `cairo_create'
 hello.c:(.text+0x4e): undefined reference to `cairo_select_font_face'
 hello.c:(.text+0x6d): undefined reference to `cairo_set_font_size'
 hello.c:(.text+0x89): undefined reference to `cairo_set_source_rgb'
 hello.c:(.text+0xbb): undefined reference to `cairo_move_to'
 hello.c:(.text+0xcc): undefined reference to `cairo_show_text'
 hello.c:(.text+0xd8): undefined reference to `cairo_destroy'
 hello.c:(.text+0xe9): undefined reference to `cairo_surface_write_to_png'
 hello.c:(.text+0xf5): undefined reference to `cairo_surface_destroy'
 collect2: error: ld returned 1 exit status

而我的源代码是:

#include <cairo.h>

int
main (int argc, char *argv[])
{
    cairo_surface_t *surface =
        cairo_image_surface_create (CAIRO_FORMAT_ARGB32, 240, 80);
    cairo_t *cr =
        cairo_create (surface);

    cairo_select_font_face (cr, "serif", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD);
    cairo_set_font_size (cr, 32.0);
    cairo_set_source_rgb (cr, 0.0, 0.0, 1.0);
    cairo_move_to (cr, 10.0, 50.0);
    cairo_show_text (cr, "Hello, world");

    cairo_destroy (cr);
    cairo_surface_write_to_png (surface, "hello.png");
    cairo_surface_destroy (surface);
    return 0;
}

如网站常见问题解答中所述。

我是使用终端命令的初学者,Cairo 是我用于图形的第一个第三方库。我试图从 Internet 上找到任何修复程序,但没有得到任何线索或修复程序。

请告诉我我的错误,并向我解释如何使用这些库。

改为这样做:

cc hello.c -o hello $(pkg-config --cflags --libs cairo)

让我们引用书中的一句话,GCC 简介 - 适用于 GNU 编译器 gcc 和 g++

The traditional behavior of linkers is to search for external functions from left to right in the libraries specified on the command line. This means that a library containing the definition of a function should appear after any source files or object files which use it. This includes libraries specified with the shortcut -l option.

根据该信息,执行:

cc -o hello $(pkg-config --cflags --libs cairo) hello.c

意味着hello.c将无法获取Cairo图形库的函数定义。

另一方面,如果您这样做:

cc hello.c -o hello $(pkg-config --cflags --libs cairo)

表示hello.c可以得到Cairo图形库的函数定义。请注意,上面的命令等效于 cc -o hello hello.c $(pkg-config --cflags --libs cairo).

更多信息here, and here