0

System Details:

NAME="Amazon Linux AMI"
VERSION="2016.03"
ID="amzn"
ID_LIKE="rhel fedora"
VERSION_ID="2016.03"
PRETTY_NAME="Amazon Linux AMI 2016.03"
POSTGRESVERSION="9.4.6"

I want to create a stored function in c to count the number of bits that are set in a bigint, so using this algorithm:

Count number of bits in a 64-bit (long, big) integer?

I wrote this code:

#include "/usr/include/pgsql92/server/postgres.h"

#ifdef
PG_MODULE_MAGIC;
#endif

int bitcardinality(unsigned long i){
        i = i - ((i >> 1) & 0x5555555555555555UL);
        i = (i & 0x3333333333333333UL) + ((i >> 2) & 0x3333333333333333UL);
        return (int) (((i + (i >> 4)) & 0xF0F0F0F0F0F0F0FUL) * 0x101010101010101UL) >> 56;
}

and compiled it as such: sudo cc -fpic -c ~/landingzone/cfuncts/bitcardinality.c sudo cc -shared -o ~/landingzone/cfuncts/bitcardinality.so ~/landingzone/cfuncts/bitcardinality.o

and placed the so in the $libdir folder, using this guide:
https://momjian.us/main/writings/pgsql/aw_pgsql_book/node170.html

I created this function creation statement:

CREATE FUNCTION bitcardinality(BIGINT bitstring)
  RETURNS BIGINT
AS '$libdir/bitcardinality.so'
LANGUAGE 'C'; 

Which gives this error:

ERROR: incompatible library "/usr/lib64/pgsql92/bitcardinality.so": missing magic block HINT: Extension libraries are required to use the PG_MODULE_MAGIC macro.

I even tried removing the #ifdef#endif but that didn't help.

Community
  • 1
  • 1
Yash Sharma
  • 293
  • 4
  • 14

1 Answers1

2

Here's the documentation on PG_MODULE_MAGIC: https://www.postgresql.org/docs/9.2/static/xfunc-c.html

It looks like the correct invocation is

#include "fmgr.h"

#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#else
#error "PG_MODULE_MAGIC wasn't defined!"
#endif

I'm surprised that what you wrote (without the identifier after #ifdef) would even be accepted by a compiler. Which compiler are you using?

Quuxplusone
  • 23,928
  • 8
  • 94
  • 159
  • Thanks I seemed to have overlooked that fmgr.h was needed, the changes you suggested fixed my issues and the stored procedure is working. I was using whichever c compiler was installed on the aws ec2 instance. Haha I can't believe I made such a silly mistake maybe I should sleep now. Thanks a lot! – Yash Sharma Jul 22 '16 at 08:00