jian
jian

Reputation: 4877

what's the properly cmakelists.txt for libpq library

I am trying to use libpq postgresql. https://pgpedia.info/l/libpq.html
I copied the exact code.Trying to understand how to use cmake. I am using Clion. (I guess the IDE doesn't matter. The following part is 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})
#target_include_directories(MyTarget PRIVATE ${/usr/include/postgresql})
include_directories("/usr/include/postgresql")

using pg_config | rg PKG command return:

PKGINCLUDEDIR = /usr/include/postgresql
PKGLIBDIR = /usr/lib/postgresql/15/lib


Also mark this related to postgresql. I copy the exact code from https://pgpedia.info/l/libpq.html to c_libpqtest.c

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

Still errors:

/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

Update: The following compile ways will work. Reference: https://riptutorial.com/postgresql/example/8018/accessing-postgresql-with-the-c-api

Shared libpq library in /usr/lib/x86_64-linux-gnu

So overall I know how to use gcc command line solve this problem. I still don't know how to use cmake to solve the problem...

Upvotes: -2

Views: 915

Answers (1)

SpacePotatoes
SpacePotatoes

Reputation: 859

CMake provides a FindPostgreSQL.cmake module file, and it defines an imported target since 3.14: https://cmake.org/cmake/help/latest/module/FindPostgreSQL.html

So the most robust approach is:

cmake_minimum_required(VERSION 3.14)
project(myproject LANGUAGES C)

find_package(PostgreSQL REQUIRED)

add_executable(myapp main.c)
target_link_libraries(myapp PRIVATE PostgreSQL::PostgreSQL)

Upvotes: 1

Related Questions