💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# 31.20\. 制作libpq程序 要制作(也就是说编译和链接)你的libpq程序, 你需要做下面的一些事情: * 包含`libpq-fe.h`头文件: ``` #include <libpq-fe.h> ``` 如果你没干这件事,那么你通常会看到类似下面这样的来自编译器的错误信息∶ ``` foo.c: In function `main': foo.c:34: `PGconn' undeclared (first use in this function) foo.c:35: `PGresult' undeclared (first use in this function) foo.c:54: `CONNECTION_BAD' undeclared (first use in this function) foo.c:68: `PGRES_COMMAND_OK' undeclared (first use in this function) foo.c:95: `PGRES_TUPLES_OK' undeclared (first use in this function) ``` * 告诉你的编译器PostgreSQL头文件的安装位置,方法是给你的编译器提供 `-I``_directory_`选项。(有些时候编译器会查找缺省的目录, 因此你可以忽略这些选项。) 比如,你的编译命令行看起来像: ``` cc -c -I/usr/local/pgsql/include testprog.c ``` 如果你在使用制作文件(makefile),那么向`CPPFLAGS`变量中增加下面的选项: ``` CPPFLAGS += -I/usr/local/pgsql/include ``` 如果你的程序可能会被别人编译,那么你应该避免像上面那样把目录路径写成硬编码。 取而代之的是你可以运行`pg_config`工具找出头文件在系统的什么地方: ``` <samp class="literal">$</samp> pg_config --includedir <samp class="literal">/usr/local/include</samp> ``` 如果你安装了`pkg-config`,你可以运行: ``` <samp class="literal">$</samp> pkg-config --cflags libpq <samp class="literal">-I/usr/local/include</samp> ``` 注意路径的前面早已包括`-I`。 如果没能给编译器提供正确的选项将产生类似下面这样的错误信息: ``` testlibpq.c:8:22: libpq-fe.h: No such file or directory ``` * 在链接最后的程序的时候,声明选项`-lpq`,这样就可以把 libpq库链接进来,还要声明 `-L``_directory_`以告诉编译器 libpq所处的目录。(同样,编译器也会搜索一些缺省的目录。) 为了尽可能提高可移植性,你应该把`-L`选项放在`-lpq`选项前面。比如: ``` cc -o testprog testprog1.o testprog2.o -L/usr/local/pgsql/lib -lpq ``` 你也可以用`pg_config`找出库目录: ``` <samp class="literal">$</samp> pg_config --libdir <samp class="literal">/usr/local/pgsql/lib</samp> ``` 或再次使用`pkg-config`: ``` <samp class="literal">$</samp> pkg-config --libs libpq <samp class="literal">-L/usr/local/pgsql/lib -lpq</samp> ``` 请注意,这会输出全部选项,而不只是路径。 指向这类问题的错误信息会是类似下面这个样子。 ``` testlibpq.o: In function `main': testlibpq.o(.text+0x60): undefined reference to `PQsetdbLogin' testlibpq.o(.text+0x71): undefined reference to `PQstatus' testlibpq.o(.text+0xa4): undefined reference to `PQerrorMessage' ``` 这意味着你忘记了`-lpq`。 ``` /usr/bin/ld: cannot find -lpq ``` 这意味着你忘记`-L`了或没有指定正确的目录。