You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为PostgreSQL的libpq库配置正确的CMakeLists.txt?

问题:CMake配置PostgreSQL libpq库编译

我尝试使用PostgreSQL的libpq库开发程序,复制了官方示例代码,希望通过CMake编译(使用Clion开发,IDE不影响问题)。

当前CMakeLists.txt内容

cmake_minimum_required(VERSION 3.23) project(test111 C)

set(CMAKE_C_STANDARD 99)
  
add_executable(test111 main.c)
find_package(PostgreSQL REQUIRED)
#target_include_directories(ecpg PUBLIC ${/usr/include/postgresql})
#target_link_libraries(ecpg PUBLIC ${PostgreSQL_LIBRARIES}
target_link_libraries(test111 PUBLIC ${/usr/lib/postgresql/15/lib})
#include_directories("/usr/include/postgresql")

pg_config相关输出

执行pg_config | rg PKG得到:

PKGINCLUDEDIR = /usr/include/postgresql

PKGLIBDIR = /usr/lib/postgresql/15/lib

未链接libpq时的GCC编译错误

将示例代码保存为c_libpqtest.c后,执行以下编译命令:

gcc -o c_assert  -I/usr/include/postgresql -L/usr/lib/postgresql/15/lib c_libpqtest.c

出现链接错误:

/usr/bin/ld: c_libpqtest.c:(.text+0x70): undefined reference to `PQstatus'
/usr/bin/ld: c_libpqtest.c:(.text+0x80): undefined reference to `PQerrorMessage'
/usr/bin/ld: c_libpqtest.c:(.text+0xbd): undefined reference to `PQexec'
/usr/bin/ld: c_libpqtest.c:(.text+0xd7): undefined reference to `PQgetvalue'
/usr/bin/ld: c_libpqtest.c:(.text+0xeb): undefined reference to `PQclear'
/usr/bin/ld: c_libpqtest.c:(.text+0xf7): undefined reference to `PQfinish'
collect2: error: ld returned 1 exit status

可行的GCC编译命令

添加-lpq链接参数后,以下命令可正常编译:

  • gcc -Wall -o c_libpq  -I/usr/include/postgresql -L/usr/lib/x86_64-linux-gnu c_libpqtest.c -lpq
    
  • gcc -Wall -o c_libpq  -I "$(pg_config --includedir)" -L "$(pg_config --libdir)" c_libpqtest.c -lpq
    
  • gcc -o c_libpq  -I/usr/include/postgresql -L/usr/lib/postgresql/14/lib c_libpqtest.c -lpq
    

共享libpq库位于/usr/lib/x86_64-linux-gnu。我已掌握GCC命令行的解决方法,但不清楚如何通过CMake正确配置。

内容的提问来源于stack exchange,提问作者jian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 07:16:30