postgresql_16:6.1.10.4 Writing Code
PostgreSQL 16 > Server Programming > Extending SQL > C-Language Functions > Writing Code
Before we turn to the more advanced topics, we should discuss some coding rules for PostgreSQL C-language functions. While it might be possible to load functions written in languages other than C into PostgreSQL, this is usually difficult (when it is possible at all) because other languages, such as C++, FORTRAN, or Pascal often do not follow the same calling convention as C. That is, other languages do not pass argument and return values between functions in the same way. For this reason, we will assume that your C-language functions are actually written in C.
The basic rules for writing and building C functions are as follows: Use pg_config --includedir-server to find out where the PostgreSQL server header files are installed on your system (or the system that your users will be running on). Compiling and linking your code so that it can be dynamically loaded into PostgreSQL always requires special flags. See (see postgresql_16:6.1.10.5) for a detailed explanation of how to do it for your particular operating system. Remember to define a “magic block” for your shared library, as described in (see postgresql_16:6.1.10.1). When allocating memory, use the PostgreSQL functions palloc and pfree instead of the corresponding C library functions malloc and free. The memory allocated by palloc will be freed automatically at the end of each transaction, preventing memory leaks. Always zero the bytes of your structures using memset (or allocate them with palloc0 in the first place). Even if you assign to each field of your structure, there might be alignment padding (holes in the structure) that contain garbage values. Without this, it's difficult to support hash indexes or hash joins, as you must pick out only the significant bits of your data structure to compute a hash. The planner also sometimes relies on comparing constants via bitwise equality, so you can get undesirable planning results if logically-equivalent values aren't bitwise equal. Most of the internal PostgreSQL types are declared in postgres.h, while the function manager interfaces (PG_FUNCTION_ARGS, etc.) are in fmgr.h, so you will need to include at least these two files. For portability reasons it's best to include postgres.h *first*, before any other system or user header files. Including postgres.h will also include elog.h and palloc.h for you. Symbol names defined within object files must not conflict with each other or with symbols defined in the PostgreSQL server executable. You will have to rename your functions or variables if you get error messages to this effect.