c++postgresqlcmakelibpqxx

Cannot use libpqxx with CMake on Mac


I have problems using libpqxx in my C++ program.

Here's main.cpp:

#include <iostream>

#include <pqxx/pqxx>

int main(int argc, const char *argv[])
{
    std::cout << "Hello, world!" << std::endl;

    try {
        pqxx::connection connection("user=iran password=irandb host=127.0.0.1 port=5432 target_session_attrs=read-write");
        std::cout << "Connected successfully!" << std::endl;
    } catch (const std::exception &e) {
        std::cerr << e.what() << std::endl;
    }

    return 0;
}

And here's CMakeLists.txt:

cmake_minimum_required(VERSION 3.25.0)

project(Main VERSION 0.1 LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

set(PostgreSQL_INCLUDE_DIR /usr/local/Cellar/postgresql@15)
set(libpqxx_DIR /usr/local/Cellar/libpqxx/7.7.5/lib/cmake)
find_package(libpqxx REQUIRED)

set(PROJECT_SOURCES src/main.cpp)

add_executable(Main ${PROJECT_SOURCES})

target_link_libraries(Main PRIVATE pqxx)

As you might've already guessed, I have installed both PostgreSQL and libpqxx via Homebrew, and for find_package() to work, I also have the following files on my system:

/usr/local/Cellar/libpqxx/7.7.5/lib/cmake/libpqxx-config.cmake /usr/local/Cellar/libpqxx/7.7.5/lib/cmake/config.cmake

which I got from here.

But, when I run cmake, the following errors occur:

CMake Error at /usr/local/Cellar/libpqxx/7.7.5/lib/cmake/libpqxx-config.cmake:4 (include):
  include could not find requested file:

    /usr/local/Cellar/libpqxx/7.7.5/lib/cmake/libpqxx-targets.cmake
Call Stack (most recent call first):
  CMakeLists.txt:10 (find_package)

Can someone please tell me what to write in my libpqxx-config.cmake file? Even if I do comment out the last line in libpqxx-config.cmake, the program encounters a runtime error as it cannot #include <pqxx/pqxx>.

P.S. I'm using an Intel-based Mac with macOS Monterey 12.6.6.


Solution

  • I found a solution in another question I posted here. It uses pkg-config.