How to fix Python CFFI error LNK2001: unresolved external symbol PyInit__...


When trying to install your Python library using a C module on Windows, you see an error message like

LINK : error LNK2001: unresolved external symbol PyInit__cv_algorithms
build\\Release\src_cv_algorithms.cp36-win_amd64.lib : fatal error LNK1120: 1 unresolved externals
error: command 'C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\link.exe' failed with exit status 1120


On Windows, CFFI does not properly generate the.

You can easily fix that by adding a template function and **including that only on windows:**I suggest creating windows.cpp like this:

 * This contains hacks to get the installation on Windows working.
 * This fixes error LNK2001: unresolved external symbol PyInit__cv_algorithms
void PyInit__cv_algorithms(void) { }

Copy & paste the name of the function from the error message! The fix will not work if you use the wrong function name.

Example how to include that file only on Windows:

platform_src = ["src/windows.cpp"] if == 'nt' else []

mod_cv_algorithms = Extension('cv_algorithms._cv_algorithms',
                         sources=['src/main.cpp'] + platform_src)

For a full example, see cv_algorithms where I first implemented this fix.