3

I have some problem writing postgres functions in C++ while following the guides for C: C-Language Functions. I found that most postgres functions are written in C instead C++, but I have to use a lib that is written in C++, so I chose C++. My question is, is there anything to notice when writing in C++? It's common to write makefiles using pgxs, so how should I write the makefile to make it work? Thanks.

3
  • 1
    One thing to think about is that you might have to mark your C++ function as extern "C". Commented Dec 14, 2011 at 7:54
  • 1
    @JoachimPileborg Alas, it's nowhere near that easy. palloc() complicates things, c++ exception handling doesn't play well with C without very defensive coding at all C/C++ interface points, and Pg's longjmp based error handling throws a major spanner into the works. Commented Dec 14, 2011 at 11:43
  • To paraphrase Linus: c++ was only created to attract idiots. Commented Dec 14, 2011 at 12:19

1 Answer 1

6

If you can avoid doing it, do so. PostgreSQL doesn't mix especially well with C++. It's possible, as shown by PostGIS, but it's not overly fun.

If you can, write or generate a pure C wrapper to your C++ library and use that wrapper to interact with the library. That won't be practical if it's heavily template based (eg: boost) or uses other more advanced C++ features, but works well if it's just C-with-objects style code. SWIG can help generate wrappers for you.

If you'd prefer to avoid the wrapper approach or if your library is a bit too complex, too exception-reliant, etc for that then you should read this PostgreSQL manual entry.

Search the PostgreSQL mailing list for more discussion on this topic.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.