How to include header file in source distribution?

Question:

I am trying to create a source distribution containing a simple c function. Here are the files I have.

# file setup.py
from setuptools import setup

setup(
    name="example",
    version="0.1",
    py_modules=["example", "build"], # If i dont include build.py, it will not find it.
    cffi_modules=["build.py:ffibuilder"],
    install_requires=["cffi"],
    setup_requires=["cffi"],
)
# file "build.py"

from cffi import FFI

ffibuilder = FFI()

SOURCE = """
#include "factorial.h"
"""

ffibuilder.cdef(
    """
long long int factorial(int n);
"""
)

ffibuilder.set_source(
    module_name="_example",
    source=SOURCE,
    sources=["factorial.c"],
    include_dirs=["."],
    library_dirs=["."],
)

if __name__ == "__main__":
    ffibuilder.compile(verbose=True)
// file "factorial.c"
#include "factorial.h"

long long int factorial(int n)
{
    long long int result = 1;
    int i;
    for (i = 1; i <= n; i++)
        result *= i;
    return result;
}
// file "factorial.h"
long long int factorial(int n);

With these files I run the command

python setup.py sdist

Which generates the file "distexample-0.1.tar.gz". And when I try to install it using

pip install example-0.1.tar.gz

I get

buildtemp.win-amd64-3.9Release_example.c(570): fatal error C1083: Cannot open include file: 'factorial.h': No such file or directory

So how do I include the header file in the source distribtuion?

Asked By: Prokie

||

Answers:

Add in the file setup.py, inside the setup function package_data={"": ["*.h"]}. This will include all the header files in the source distribution.

setup(
    name="example",
    version="0.1",
    py_modules=["example", "build"], # If i dont include build.py, it will not find it.
    cffi_modules=["build.py:ffibuilder"],
    install_requires=["cffi"],
    setup_requires=["cffi"],
    package_data={"": ["*.h"]} # <- This line
)
Answered By: Prokie

Instead of package_data, you could also use a MANIFEST.in file as per 4. Building C and C++ Extensions.

In some cases, additional files need to be included in a source distribution; this is done through a MANIFEST.in file; see Specifying the files to distribute for details.

For example, in numpy and pytorch, in their MANIFEST.in, they include all files in specified folders, which includes header files.

Answered By: Ben Butterworth
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.