PostgreSQL 編譯 libpq 程序

2021-09-02 13:48 更新

要編譯(即編譯并且鏈接)一個使用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)
    

  • 通過為你的編譯器提供-Idirectory 選項,向你的編譯器指出PostgreSQL頭文件安裝在哪里(在某些情況下編譯器默認(rèn)將查看該目錄,因此你可以忽略這個選項)。例如你的編譯命令行可能看起來像:

    cc -c -I/usr/local/pgsql/include testprog.c
    

    如果你在使用 makefile,那么把該選項加到CPPFLAGS變量中:

    CPPFLAGS += -I/usr/local/pgsql/include
    

    如果你的程序可能由其他用戶編譯,那么你不應(yīng)該像那樣硬編碼目錄位置。你可以運行工具pg_config 在本地系統(tǒng)上找出頭文件在哪里:

    $ pg_config --includedir
    /usr/local/include
    

    如果你安裝了pkg-config ,你可以運行:

    $ pkg-config --cflags libpq
    -I/usr/local/include
    

    注意這將在路徑前面包括-I

    無法為編譯器指定正確的選項將導(dǎo)致一個錯誤消息,例如:

    testlibpq.c:8:22: libpq-fe.h: No such file or directory
    

  • 當(dāng)鏈接最終的程序時,指定選項-lpq,這樣libpq庫會被編譯進去,也可以用選項-Ldirectory 向編譯器指出libpq庫所在的位置(再次,編譯器將默認(rèn)搜索某些目錄)。為了最大的可移植性,將-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'
    

    This means you forgot -lpq.

    /usr/bin/ld: cannot find -lpq
    

    這意味著你忘記了-L選項或者沒有指定正確的目錄。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號