c++postgresqllibpqxx

Compiling a JNI file with c++ postgresql in command prompt getting fatal error


Command executed:

g++ -I"C:\Program Files\Java\jdk-16.0.2\include" -I"C:\Program Files\Java\jdk-16.0.2\include\win32" -I"C:\Program Files\libpqxx\include\pqxx" -shared -o hello.dll HelloJNI.cpp

pqxx file dir - C:\Program Files\libpqxx\include

I have included the path with -I .

I am using C++ for the backend connection for my Java program using JNI and unable to compile the cpp file, getting error as:


HelloJNI.cpp:4:10: fatal error: pqxx/pqxx: No such file or director
    4 | #include <pqxx/pqxx>
      |          ^~~~~~~~~~~
compilation terminated.

The executed code is:

#include <jni.h>       // JNI header provided by JDK
#include <iostream>    // C++ standard IO header
#include "HelloJNI.h"  // Generated
#include <pqxx/pqxx>
#include <string>
using namespace std;

// Implementation of the native method sayHello()
JNIEXPORT void JNICALL Java_HelloJNI_sayHello(JNIEnv *env, jobject thisObj) 
{
     try
    {
        std::string connectionString = "host=localhost port=5432 dbname=postgres user=postgres password =caNarain@2002";

        pqxx::connection connectionObject(connectionString.c_str());

        pqxx::work worker(connectionObject);

        pqxx::result response = worker.exec("SELECT * FROM books ORDER BY BOOK_ID");

        for (size_t i = 0; i < response.size(); i++)
        {
            std::cout << response[i][0] << " " << response[i][1] << " " << response[i][2] << " " << response[i][3] << " " << response[i][4] << " " << response[i][5] << std::endl;
        }

        return;
    }
    catch (const std::exception& e)
    {
        std::cerr << e.what() << std::endl;
    }

    system("pause");
}


Solution

  • Compile the file in visual studio.

    Add the paths to the respective fields like additional include directories, linker files in the property.

    conclude the JNIEXPORT void JNICALL Java_HelloJNI_sayHello(JNIEnv *env, jobject thisObj)

    inside a int main() method to compile since visual studio cannot compile the files without main method.

    you can follow same as cmdline if your program doesn't have postgresql.