32.21. Сборка программ с 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. (В некоторых случаях компилятор сам может обращаться к нужному каталогу, так что этот параметр можно опустить.) Например, ваша команда компиляции может быть такой:каталогcc -c -I/usr/local/pgsql/include testprog.c
Если вы используете скрипты сборки Makefile, добавьте этот параметр в переменную
CPPFLAGS:CPPFLAGS += -I/usr/local/pgsql/include
Если существует возможность, что вашу программу будут компилировать другие пользователи, то путь к каталогу не следует жёстко задавать таким образом. Вместо этого вы можете воспользоваться утилитой
pg_configи узнать, где в локальной системе находятся заголовочные файлы, следующим образом:$pg_config --includedir/usr/local/includeЕсли у вас установлена программа
pkg-config, вместо этого вы можете выполнить:$pkg-config --cflags libpq-I/usr/local/includeЗаметьте, что при этом перед путём сразу будет добавлен ключ
-I.Если требуемый параметр не будет передан компилятору, вы получите примерно такое сообщение об ошибке:
testlibpq.c:8:22: libpq-fe.h: No such file or directory
При компоновке окончательной программы добавьте параметр
-lpq, чтобы была подключена библиотека libpq, а также параметр-L, указывающий на каталог, в котором находится libpq. (Опять же, компилятор будет просматривать определённые каталоги по умолчанию.) Для максимальной переносимости указывайте ключкаталог-Lперед параметром-lpq. Например:cc -o testprog testprog1.o testprog2.o -L/usr/local/pgsql/lib -lpq
Каталог с библиотекой можно узнать, так же используя
pg_config:$pg_config --libdir/usr/local/pgsql/libИли с помощью той же программы
pkg-config:$pkg-config --libs libpq-L/usr/local/pgsql/lib -lpqЗаметьте, что и в этом случае выводится полностью сформированный параметр, а не только путь.
В случае проблем в этой области возможны примерно такие сообщения об ошибках:
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или не указали правильный каталог.
32.21. Building libpq Programs #
To build (i.e., compile and link) a program using libpq you need to do all of the following things:
Include the
libpq-fe.hheader file:#include <libpq-fe.h>
If you failed to do that then you will normally get error messages from your compiler similar to:
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)
Point your compiler to the directory where the PostgreSQL header files were installed, by supplying the
-Ioption to your compiler. (In some cases the compiler will look into the directory in question by default, so you can omit this option.) For instance, your compile command line could look like:directorycc -c -I/usr/local/pgsql/include testprog.c
If you are using makefiles then add the option to the
CPPFLAGSvariable:CPPFLAGS += -I/usr/local/pgsql/include
If there is any chance that your program might be compiled by other users then you should not hardcode the directory location like that. Instead, you can run the utility
pg_configto find out where the header files are on the local system:$pg_config --includedir/usr/local/includeIf you have
pkg-configinstalled, you can run instead:$pkg-config --cflags libpq-I/usr/local/includeNote that this will already include the
-Iin front of the path.Failure to specify the correct option to the compiler will result in an error message such as:
testlibpq.c:8:22: libpq-fe.h: No such file or directory
When linking the final program, specify the option
-lpqso that the libpq library gets pulled in, as well as the option-Lto point the compiler to the directory where the libpq library resides. (Again, the compiler will search some directories by default.) For maximum portability, put thedirectory-Loption before the-lpqoption. For example:cc -o testprog testprog1.o testprog2.o -L/usr/local/pgsql/lib -lpq
You can find out the library directory using
pg_configas well:$pg_config --libdir/usr/local/pgsql/libOr again use
pkg-config:$pkg-config --libs libpq-L/usr/local/pgsql/lib -lpqNote again that this prints the full options, not only the path.
Error messages that point to problems in this area could look like the following:
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'
This means you forgot
-lpq./usr/bin/ld: cannot find -lpq
This means you forgot the
-Loption or did not specify the right directory.