Re: How to compile, link and use a C++ extension - Mailing list pgsql-hackers

From Craig Ringer
Subject Re: How to compile, link and use a C++ extension
Date
Msg-id CAMsr+YG+k7a6TA59DOvtGAhz0u0t7+pSnZUY3omzAvqtj=bsuA@mail.gmail.com
Whole thread Raw
In response to Re: How to compile, link and use a C++ extension  (Andres Freund <andres@anarazel.de>)
List pgsql-hackers
On 15 August 2015 at 00:51, Andres Freund <andres@anarazel.de> wrote:

>> I started my tests by cloning the contrib/worker_spi code, and when
>> transforming the code into C++, I could only note that C++ is not supported
>> in the provided Makefiles.
>
> Yes, that doesn't surprise me. Postgres itself doesn't need to care
> about looking for a usable C++ compiler et al.

I think it'd be necessary to add C++ support to PGXS to do this nicely.

Because PostgreSQL's headers have C++
   extern "C" {

wrappers in them, you could potentially compile the whole extension
g++, using "extern C" to expose unmangled symbols. You'll run into
some issues due to incompatible compiler flags, though:

$ PATH=$HOME/pg/95/bin:$PATH make USE_PGXS=1 CC=g++
g++ -Wall -Wmissing-prototypes -Wpointer-arith
-Wdeclaration-after-statement -Wendif-labels
-Wmissing-format-attribute -Wformat-security -fno-strict-aliasing
-fwrapv -fexcess-precision=standard -O2 -fpic -I. -I./
-I/home/craig/pg/95/include/postgresql/server
-I/home/craig/pg/95/include/postgresql/internal -D_GNU_SOURCE   -c -o
worker_spi.o worker_spi.c
cc1plus: warning: command line option ‘-Wmissing-prototypes’ is valid
for C/ObjC but not for C++
cc1plus: warning: command line option ‘-Wdeclaration-after-statement’
is valid for C/ObjC but not for C++
cc1plus: sorry, unimplemented: -fexcess-precision=standard for C++
<builtin>: recipe for target 'worker_spi.o' failed
make: *** [worker_spi.o] Error 1


> How exactly do you need to use the C++ code? The easiest probably would
> be to have a separate object file, built using your own makefile rule,
> that contains a the C++ and provides a C interface, and then use that
> from a background worker purely written in C.

This is what I would advise too.

It helps to separate the PostgreSQL bits from the C++ bits, providing
a clean interface across which exceptions are not thrown.

It isn't safe to access PostgreSQL API from within your C++ code
anyway, so the C++ code can be compiled without any PostgreSQL
includes, exposing a pure C interface that your extension can then
link to as just another library via PGXS's SHLIB_LINK option.

-- Craig Ringer                   http://www.2ndQuadrant.com/PostgreSQL Development, 24x7 Support, Training & Services



pgsql-hackers by date:

Previous
From: Craig Ringer
Date:
Subject: Re: More WITH
Next
From: Tom Lane
Date:
Subject: Re: More WITH