0

I'm trying to use libxml2 on a c++ project, but i cant seem to manage to link the libraries correctly.

Here is parser.cpp (parse() comes from an example on xmlsoft.org)

#include <iostream> 
#include <stdio.h>
extern "C" 
{
    #include <libxml/xmlreader.h>
    #include <libxml/parser.h>
    #include <libxml/tree.h>
}
using namespace std; 
void processNode(xmlTextReaderPtr reader){
    if(reader!=NULL){
        cout << "not null\n"<<endl;
    }
}
void parse(const char *xmlFile){
    xmlTextReaderPtr reader;
    int ret;

    reader = xmlReaderForFile(xmlFile, NULL, 0);
    if (reader != NULL) {
        ret = xmlTextReaderRead(reader);
        while (ret == 1) {
            processNode(reader);
            ret = xmlTextReaderRead(reader);
        }
        xmlFreeTextReader(reader);
        if (ret != 0) {
            fprintf(stderr, "%s : failed to parse\n", xmlFile);
        }
    } else {
        fprintf(stderr, "Unable to open %s\n", xmlFile);
    }
}

int main(int argc, char** argv) 
{ 
    if(argc < 2){
        cout << "Please provide an XML file as Argument \n"<<endl;
    }
    parse(argv[1]);  
    return 0; 
} 

I compile it with

g++ -I/usr/local/include/libxml2 parser.cpp

and i get the following error:

/usr/bin/ld: /tmp/ccaeOdco.o: in function `parse(char const*)':
parser.cpp:(.text+0x64): undefined reference to `xmlReaderForFile'
/usr/bin/ld: parser.cpp:(.text+0x7b): undefined reference to `xmlTextReaderRead'
/usr/bin/ld: parser.cpp:(.text+0x9c): undefined reference to `xmlTextReaderRead'
/usr/bin/ld: parser.cpp:(.text+0xad): undefined reference to `xmlFreeTextReader'
collect2: error: ld returned 1 exit status

I have verified that functions exist on the included files. What am I doing wrong?

Frant
  • 4,492
  • 1
  • 14
  • 21
  • 1
    You're not actually linking the library (just setting the include directory). Try adding -L to the g++ command – perivesta Oct 16 '20 at 13:42
  • 2
    Add the -lxml2 compiler switch to link with libxml2, everything else seems to be fine. This way the linker uses the compiled/installed libxml2.a & .so files – Viktor Latypov Oct 16 '20 at 13:57
  • Already tried that. the `*.a` and `*.so` files are on `/usr/local/lib` and when i add `-llibxml2`, `ld` complains `/usr/bin/ld: cannot find -llibxml`. Same with full path. When i use` -L`, nothing changes, same output as if im not using it. – Fisnik Hajredini Oct 16 '20 at 14:17
  • 1
    Do `-lxml2`, not `-llibxml2`. – Anonymous1847 Oct 16 '20 at 16:34
  • Does this answer your question? [What is an undefined reference/unresolved external symbol error and how do I fix it?](https://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix) – Ken White Oct 16 '20 at 18:34

0 Answers0