How to make PostgreSQL to load a C-module that depends on a DLL?
<p>I have tried without success to create a C-language function in PostgreSQL from a module that depends on another DLL in Windows.</p>

<p>For example, let's suppose I want to create the <code>sum</code>function that adds two numbers returned by the <code>number</code>function that is in its own DLL.</p>

<p>The code for <code>number.h</code> is:</p>

<pre><code>#ifndef NUMBER_H
#define NUMBER_H

#ifdef NUMBER_EXPORTS
#define NUMBER_API __declspec(dllexport)
#else
#define NUMBER_API __declspec(dllimport)
#endif

extern "C" NUMBER_API int number();

#endif
</code></pre>

<p>and the code for <code>number.cpp</code> is:</p>

<pre><code>#include "number.h"
extern "C" int number() { return 1; }
</code></pre>

<p>The code for <code>sum.cpp</code> is:</p>

<pre><code>extern "C" {

#include &lt;postgres.h&gt;
#include &lt;fmgr.h&gt;
#include &lt;utils/geo_decls.h&gt;
#include "number.h"

#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif

__declspec(dllexport) PG_FUNCTION_INFO_V1(sum);

Datum sum(PG_FUNCTION_ARGS)
{
    int32 a {number()};
    int32 b {number()};
    int32 result {a + b};
    PG_RETURN_INT32(result);
}

} // extern "C"
</code></pre>

<p>Suppossing that PostgreSQL is installed on <code>C:\Program Files\PostgreSQL\9.5</code>, I create <code>number.dll</code> and <code>sum.dll</code> using this <code>build.bat</code> file:</p>

<pre><code>SET PG_DIR=C:\Program Files\PostgreSQL\9.5
SET PG_INCLUDES=/I%PG_DIR%\include /I%PG_DIR%\include\server /I%PG_DIR%\include\server\port\win32
CL number.cpp /EHsc /MD /DNUMBER_EXPORTS /LD
CL sum.cpp /EHsc /MD %PG_INCLUDES% /LD /link number.lib
</code></pre>

<p>Then I copy both DLLs to <code>C:\Program Files\PostgreSQL\9.5\lib</code> and write the SQL for creating the function in <code>sum.sql</code>:</p>

<pre><code>CREATE OR REPLACE FUNCTION sum() RETURNS void AS
'sum'
LANGUAGE C STRICT;
</code></pre>

<p>After running <code>psql -U postgres -f sum.sql</code>, I get the following error:</p>

<pre><code>psql:sum.sql:3: ERROR:  could not load library "C:/Program Files/PostgreSQL/9.5/lib/sum.dll": The specified module could not be found.
</code></pre>

<p>Note that this error is different from a "file not found" error. It seems that PostgreSQL finds the file, but does not recognize it as a valid module. However, if I create a static library of <code>num.cpp</code> instead and link it against <code>sum.dll</code>, then the function is created successfully. In other words, PostgreSQL loads the module only if it contains all the code it needs.</p>

<p>Why is this happening and how could I make PostgreSQL to know about <code>number.dll</code> when creating the <code>sum</code> function?</p>