Linking PostgreSQL as a C++ program

Started by Craig Ringeralmost 8 years ago3 messages
#1Craig Ringer
craig@2ndquadrant.com

Hi all

In my ongoing efforts to make Tom look at me in horror, I've compiled
PostgreSQL with C++ objects linked into the core server. Currently this is
just my notes on how, in case anyone else needs to later.

To do it you really only have to change src/backend/Makefile to use g++ as
a linker:

 postgres: $(OBJS)
-    $(CC) $(CFLAGS) $(LDFLAGS) $(LDFLAGS_EX) $(export_dynamic) $(call
expand_subsys,$^) $(LIBS) -o $@
+    $(CXX) $(CFLAGS) $(LDFLAGS) $(LDFLAGS_EX) $(export_dynamic) $(call
expand_subsys,$^) $(LIBS) -o $@

so it links to libstdc++.

To use the postgres headers within C++ code you must also:

extern "C" {
#include "postgres.h"
}

since we only do that automagically for the frontend headers.

Currently it's also necessary to add a "_THROW" annotation to
src/include/port.h's definition of inet_net_ntop to stop it conflicting
with <inet/arpa.h>'s definition.

The Makefiles already support building and linking C++ objects, so a normal
Makefile can specify c++ sources in "OBJS", e.g. "blah.o" will get compiled
from "blah.cpp".

If what I'm prototyping works out I'll do my best to move it into an
extension, because I can just imagine how likely a patch that adds c++11
code to the core server would be to get accepted ;)

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

#2Michael Paquier
michael.paquier@gmail.com
In reply to: Craig Ringer (#1)
Re: Linking PostgreSQL as a C++ program

On Mon, Jan 29, 2018 at 05:46:54PM +1300, Craig Ringer wrote:

extern "C" {
#include "postgres.h"
}

Don't you need __cplusplus as well? More or less that:

#ifdef __cplusplus
extern "C" {
#endif
#include "postgres.h"
#ifdef __cplusplus
}
#endif
--
Michael

#3Craig Ringer
craig@2ndquadrant.com
In reply to: Michael Paquier (#2)
Re: Linking PostgreSQL as a C++ program

On 29 January 2018 at 18:02, Michael Paquier <michael.paquier@gmail.com>
wrote:

On Mon, Jan 29, 2018 at 05:46:54PM +1300, Craig Ringer wrote:

extern "C" {
#include "postgres.h"
}

Don't you need __cplusplus as well? More or less that:

#ifdef __cplusplus
extern "C" {
#endif
#include "postgres.h"
#ifdef __cplusplus
}
#endif

For headers used by both C and C++ code, yes.

For C++ sources, no.

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