C语言解析xml文件遇到的一个编译问题
在用libxml2尝试做解析xml文件,编译的时候出现了找不到头文件的错误:
?
[nigelzeng@myhost xml-learning]$ gcc -o xml-build xml-build.c xml-build.c:4:30: libxml/xmlmemory.h: 没有那个文件或目录xml-build.c:5:27: libxml/parser.h: 没有那个文件或目录xml-build.c:8: error: syntax error before "doc"xml-build.c: In function `parseStory':xml-build.c:9: error: `xmlChar' undeclared (first use in this function)xml-build.c:9: error: (Each undeclared identifier is reported only oncexml-build.c:9: error: for each function it appears in.)……
?
?
问题出自啊c文件里的include:
?
#include <libxml/xmlmemory.h>#include <libxml/parser.h>
?
?
默认会到/usr/include 目录下搜索,但是不存在libxml目录,而libxml是在/usr/include/libxml2/libxml 下。
所以我先做了一个软连接:
?
[nigelzeng@myhost xml-learning]$ ln -s /usr/include/libxml2/libxml /usr/include/libxml
?
?
再尝试着编译,路径的问题是解决了,但是链接库的问题还在,内建的函数找不到:
?
[nigelzeng@myhost xml-learning]$ gcc -o xml-build xml-build.c/tmp/cc62WqCk.o(.text+0x24): In function `parseStory':: undefined reference to `xmlStrcmp'/tmp/cc62WqCk.o(.text+0x3e): In function `parseStory':: undefined reference to `xmlNodeListGetString'/tmp/cc62WqCk.o(.text+0x62): In function `parseStory':: undefined reference to `xmlFree'/tmp/cc62WqCk.o(.text+0x85): In function `parseDoc':: undefined reference to `xmlParseFile'/tmp/cc62WqCk.o(.text+0xb7): In function `parseDoc':: undefined reference to `xmlDocGetRootElement'/tmp/cc62WqCk.o(.text+0xe4): In function `parseDoc':: undefined reference to `xmlFreeDoc'/tmp/cc62WqCk.o(.text+0xff): In function `parseDoc':: undefined reference to `xmlStrcmp'/tmp/cc62WqCk.o(.text+0x127): In function `parseDoc':: undefined reference to `xmlFreeDoc'/tmp/cc62WqCk.o(.text+0x14e): In function `parseDoc':: undefined reference to `xmlStrcmp'/tmp/cc62WqCk.o(.text+0x17c): In function `parseDoc':: undefined reference to `xmlFreeDoc'collect2: ld returned 1 exit status
?
?
在网上搜索了下答案,可以在gcc命令后加上 -I?和 -l 参数解决:
?
[nigelzeng@myhost xml-learning]$ gcc -o xml-build xml-build.c -I/usr/include/libxml2/ -lxml2
?
?
用这个命令,所有的错误都解决了,成功编译出来需要的执行文件。
?
这个 -I 和 -l 的参数解释是这样的:
“
-Idir当用#include <file> 链接文件的时候,gcc/g++会先在当前目录查找你所制定的头文件,如果没有找到,他回到缺省的头文件目录找,如果使用-I制定了目录,他会先在你所制定的目录查找,然后再按常规的顺序去找。
?
-llibrary制定编译的时候使用的库。
例子用法: gcc -lcurses hello.c ? /* 使用ncurses库编译程序 */
”
?
所以“gcc -o xml-build xml-build.c -I/usr/include/libxml2/ -lxml2”命令的意思就是“在指定目录/usr/include/libxml2里寻找头文件,编译时使用的库是xml2函数库”
?
?
ps:
这个命令也可以成功编译:gcc `xml2-config --cflags --libs` -o xml-create xml-create.c
?