cpostgresqlpostgresql-12ecpg

Postgres ECPG: adding a function outside main() breaks the program


I have successfully connected and obtained data from Postgresql with my C application. My connector.pgc file looks like this:

#include <stdlib.h>
#include <stdio.h>
//#include "connect.h" // PROBLEM

int connect(); //NO PROBLEM

EXEC SQL BEGIN DECLARE SECTION;
    char dbname[1024];
    const char *target = "dbname@host:port";
    const char *user = "user";
    const char *passwd = "password";
EXEC SQL END DECLARE SECTION;

int main() {
    EXEC SQL CONNECT TO :target AS con1 USER :user USING :passwd;
    EXEC SQL SELECT pg_catalog.set_config('search_path', 'schema_name', false); EXEC SQL COMMIT;

    EXEC SQL SET CONNECTION con1;

    EXEC SQL SELECT current_database() INTO :dbname;
    printf("current database is '%s'\n", dbname);
    
    EXEC SQL DISCONNECT ALL;
    // connect();
    return 0;
}

// PROBLEM
//int connect(){
//    printf("A\n");
//    return 0;
//}

except, of course, username/password/schema_name/etc. are replaced with actual values. I then do the following:

ecpg connector.pgc && gcc connector.c -o connectorXec -lecpg -L/usr/pgsql-12/lib && ./connectorXec

My operating system is a default CentOS 8.
ecpg --version returns ecpg (PostgreSQL) 13.2
psql --version returns psql (PostgreSQL) 12.8

The program compiles fine and I am able to connect without issues, the way I know this is printf extracts the correct database name, and I've also run other SQL SELECTS to confirm the data.

However, as soon as I uncomment the int connect() function, even without using it, it is called 3 times before the actual program, and I do not know why. To be more precise, I see the letter A being printed 3 times. Additionally, printf no longer displays the correct name, instead dbname is empty.

I tried putting int connect() function into a separate connect.c file, then linking it together with this program through connect.h, and the result is the same.

If I put the contents of main() into connect(), and then call it, the process just hangs indefinitely.

Truly, I am at a loss, and I do not have even the slightest idea of where to begin, since this situation seems impossible. I checked the connector.c file that ECPG produces and there are no additional calls. Most references I can find online contain only main() function, and in rare cases where they do not, there is no mention of any remotely similar issue.

Any ideas as to what's going on?


Solution

  • OK, so it turns out the connect() function is used somewhere, since renaming it solved the issue. I was renaming it in the created connector.c file, which is how I missed this obvious solution.

    Laurenz Albe said that he tried this on his end and everything is fine, which means it is somehow unique to my setup.