To compile and link your libpq programs you need to do all of the following things:
Include the libpq-fe.h header file:
#include <libpq-fe.h> |
If you fail to include libpq-fe.h, you will see compiler errors similar to these:
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) |
Use the -Idirectory option with your compiler command to point the compiler to the directory where the Red Hat Database header files were installed. (In some cases the compiler will look into that directory by default, so you may be able to omit this option.)
For example, your compiler command line could be similar to the following:
gcc -c -I/usr/include/pgsql testprog.c |
If you are using makefiles, add the option to the CPPFLAGS variable:
CPPFLAGS += -I/usr/include/pgsql |
You should run the utility pg_config to find out where the header files are located on the system:
$ pg_config --includedir |
which gives:
/usr/include/pgsql |
If you fail to specify a library directory to the compiler, you will see an error message similar to:
testlibpq.c:8:22 libpq-fe.h: No such file or directory |
When linking the final program, specify the option -lpq so that the libpq library gets pulled in, as well as the option -Ldirectory to point it to the libpq library's directory. (Again, the compiler will search some directories by default, such as the /usr/lib directory below.) For maximum portability, put the -L option before the -lpq option. For example:
gcc -o testpg testpg1.o testpg2.o -L/usr/lib -lpq |
You can find the library directory using pg_config:
$ pg_config --libdir |
which gives:
/usr/lib |
If you forget to include -lpq, you may see errors similar to these:
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' |
If you forget the -L or if you specify the wrong path, you will see:
/usr/bin/ld: cannot find -lpq |