7

I have a simple example for libxml2 but it returns the following error:

$ gcc -Wall -lxml2 -I/usr/include/libxml2 -o ex1 ex1.c
/tmp/cc6OKSKJ.o: In function `main':
ex1.c:(.text+0x60): undefined reference to `xmlReadFile'
ex1.c:(.text+0x70): undefined reference to `xmlDocGetRootElement'
collect2: ld returned 1 exit status
$ xml2-config --libs
-lxml2
$ xml2-config --cflags
-I/usr/include/libxml2

I'm on Lubuntu 11.10 x86_64 and I have all the packages I need (well I think): libxml2, libxml2-dev, libxml2-dbg... Here's the code of the example:

// gcc -Wall -lxml2 -I/usr/include/libxml2 -o ex1 ex1.c

#include <stdio.h>
#include <string.h>
#include <libxml/parser.h>

int main(int argc, char **argv)
{
    xmlDoc *document;
    xmlNode *root, *first_child, *node;
    char *filename;

    if (argc < 2)
    {
        fprintf(stderr, "Usage: %s filename.xml\n", argv[0]);
        return 1;
    }
    filename = argv[1];

    document = xmlReadFile(filename, NULL, 0);
    root = xmlDocGetRootElement(document);
    fprintf(stdout, "Root is <%s> (%i)\n", root->name, root->type);
    first_child = root->children;

    for (node = first_child; node; node = node->next)
    {
        fprintf(stdout, "\t Child is <%s> (%i)\n", node->name, node->type);
    }
    fprintf(stdout, "...\n");
    return 0;
}
Suugaku
  • 2,667
  • 5
  • 31
  • 33
  • Check that gcc is compiling for the same architecture as the libxml2 libraries you are using (in particulat ensure that one is not x86_64 and the other i386). It seems unlikely that this would be the culprit, but its worth checking. – Michael Anderson Oct 19 '11 at 02:11

1 Answers1

18

Your link line is incorrect. Try

gcc -Wall -I/usr/include/libxml2 -o ex1 ex1.c -lxml2

Read this to understand why the order of sources and libraries on command line matters.

Employed Russian
  • 199,314
  • 34
  • 295
  • 362
  • 1
    Do you think for shared libraries the order will matter? The link discusses about *static* libraries. I am able to compile it on Ubuntu 10.04 (32bit) w/o any problem the way OP is trying to and there is just only one library "libxml" being linked (apart from the standard ones like libc, ld etc ofc) – another.anon.coward Oct 19 '11 at 05:47
  • I could never imagine the order mattered but yes, for me it works only with -lxml2 at the end. – Suugaku Oct 19 '11 at 06:16
  • 1
    instead of -I/usr/include/libxml2 use $(xml2-config --cflags) – the.malkolm Feb 28 '12 at 10:35
  • Doesn't work for a cross-compile for this. Works fine with host compile, but when you do it to the target, it borks up on the link Can't easily deal with link order because it's all automagic with Autotools. (Fail...) – Svartalf Jul 27 '15 at 23:06