如何链接X11程序

时间:2014-01-11 22:46:19

标签: c linker x11

我已经编译了第一个X11程序,但无法链接它。我在64位Xubuntu 13.10上,我使用命令行 gcc $(pkg-config x11)findXfonts.c -o findXfonts

它编译好了,但我使用的每个X *符号在链接器步骤中显示为未定义。 pkg-config惯用语扩展为-lX11

/*
 * Copyright 2014 Kevin O'Gorman <kogorman@gmail.com>.
 * Distributed under the GNU General Public License.
 *
 * This is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 */

#include <stdlib.h>
#include <unistd.h>
#include <X11/Xlib.h>
#include <stdio.h>

int
main(int argc, char *argv[])
{
  char **fontlist;
  XFontStruct *returned_info;
  char *pattern="-*-*-*-*-*-*-*-*-*-*-*-*-*-*-";
  int nFonts;
  char *displayName;
  Display *display;
  FILE *ostream = stdout;
  int i, j, k;

  displayName = getenv("DISPLAY");        /* expect ":0.0", but YMMV */
  display = XOpenDisplay(displayName);
  fontlist = XListFontsWithInfo(display, pattern, 10000, &nFonts, &returned_info);

  for (i = 0; i < nFonts; i++) {
    fprintf(ostream, "\n%s\n", fontlist[i]);
    fprintf(ostream, "   first: %u/%u, last: %u/%u\n",
        returned_info[i].min_byte1, returned_info[i].min_char_or_byte2,
        returned_info[i].max_byte1, returned_info[i].max_char_or_byte2);
    for (j = 0; j < returned_info[i].n_properties; j++) {
      fprintf(ostream, "      %s: %ld\n", 
          XGetAtomName(display, returned_info[i].properties[j].name),
          returned_info[i].properties[j].card32);
    }
  }

  XFreeFontInfo(fontlist, returned_info, nFonts);
  return EXIT_SUCCESS;
}

3 个答案:

答案 0 :(得分:2)

尝试:

gcc $(pkg-config x11 --cflags) findXfonts.c -o findXfonts $(pkg-config x11 --libs)

然后阅读pkg-config的手册页:

man pkg-config

答案 1 :(得分:2)

是错误的
  

pkg-config惯用法扩展为-lX11

实际上如果你试试

echo $(pkg-config x11)
你什么也得不到。代替

echo $(pkg-config x11  --cflags --libs)

输出(在我的系统上)

-lX11

这是您想要的,您需要的只是在系统上正确设置的所有内容,以便编译和开发X11代码。

因此,在--cflags --libs内添加$(...)就足够了。

答案 2 :(得分:0)

有三个问题。

首先,我将--libs切换到pkg-config。 ( - cflags开关在这种情况下没有贡献)。我也把它放在命令行中的错误位置。

其次,链接器找不到X11库。我不得不告诉它要查看哪个目录。有些人为此使用LD_LIBRARY_PATH,但由于我有64位和32位库,所以我不想采用单一方法。

最后,我制作了一个Makefile,最后以

结束
gcc -Wall -ansi -g -m64 -c findXfonts.c
gcc findXfonts.o -m64 -L/usr/lib/x86_64-linux-gnu -lX11 -o findXfonts

最后,一旦编译和链接,我发现“模式”字符串末尾有一个额外的连字符(“ - ”)。我删除了它,并获得了1400多种字体列表。