2This module provides helpers for C++11+ projects using pybind11.
6Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>, All rights reserved.
8Redistribution and use in source and binary forms, with or without
9modification, are permitted provided that the following conditions are met:
111. Redistributions of source code must retain the above copyright notice, this
12 list of conditions and the following disclaimer.
142. Redistributions
in binary form must reproduce the above copyright notice,
15 this list of conditions
and the following disclaimer
in the documentation
16 and/
or other materials provided
with the distribution.
183. Neither the name of the copyright holder nor the names of its contributors
19 may be used to endorse
or promote products derived
from this software
20 without specific prior written permission.
22THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND
23ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
24WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
25DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
26FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
28SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
29CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34# IMPORTANT: If you change this file in the pybind11 repo, also review
35# setup_helpers.pyi for matching changes.
37# If you copy this file in, you don't
38# need the .pyi file; it's just an interface file for static type checkers.
50from functools import lru_cache
51from pathlib import Path
66 from setuptools
import Extension
as _Extension
67 from setuptools.command.build_ext
import build_ext
as _build_ext
69 from distutils.command.build_ext
import build_ext
as _build_ext
70 from distutils.extension
import Extension
as _Extension
72import distutils.ccompiler
73import distutils.errors
75WIN = sys.platform.startswith(
"win32")
and "mingw" not in sysconfig.get_platform()
76MACOS = sys.platform.startswith(
"darwin")
77STD_TMPL =
"/std:c++{}" if WIN
else "-std=c++{}"
87class Pybind11Extension(_Extension):
89 Build a C++11+ Extension module with pybind11. This automatically adds the
90 recommended flags when you init the extension
and assumes C++ sources - you
91 can further modify the options yourself.
93 The customizations are:
95 * ``/EHsc``
and ``/bigobj`` on Windows
96 * ``stdlib=libc++`` on macOS
97 * ``visibility=hidden``
and ``-g0`` on Unix
99 Finally, you can set ``cxx_std`` via constructor
or afterwards to enable
100 flags
for C++ std,
and a few extra helper flags related to the C++ standard
101 level. It
is _highly_ recommended you either set this,
or use the provided
102 ``build_ext``, which will search
for the highest supported extension
for
103 you
if the ``cxx_std`` property
is not set. Do
not set the ``cxx_std``
104 property more than once,
as flags are added when you set it. Set the
105 property to
None to disable the addition of C++ standard flags.
107 If you want to add pybind11 headers manually,
for example
for an exact
108 git checkout, then set ``include_pybind11=
False``.
115 self.extra_compile_args[:0] = flags
118 self.extra_link_args[:0] = flags
120 def __init__(self, *args: Any, **kwargs: Any) ->
None:
122 cxx_std = kwargs.pop(
"cxx_std", 0)
124 if "language" not in kwargs:
125 kwargs[
"language"] =
"c++"
127 include_pybind11 = kwargs.pop(
"include_pybind11",
True)
137 pyinc = pybind11.get_include()
139 if pyinc
not in self.include_dirs:
140 self.include_dirs.append(pyinc)
141 except ModuleNotFoundError:
149 cflags += [
"/EHsc",
"/bigobj"]
151 cflags += [
"-fvisibility=hidden"]
152 env_cflags = os.environ.get(
"CFLAGS",
"")
153 env_cppflags = os.environ.get(
"CPPFLAGS",
"")
154 c_cpp_flags = shlex.split(env_cflags) + shlex.split(env_cppflags)
155 if not any(opt.startswith(
"-g")
for opt
in c_cpp_flags):
158 cflags += [
"-stdlib=libc++"]
159 ldflags += [
"-stdlib=libc++"]
166 The CXX standard level. If set, will add the required flags. If left at
167 0, it will trigger an automatic search when pybind11's build_ext is
168 used. If None, will have no effect. Besides just the flags, this may
169 add a macos-min 10.9
or 10.14 flag
if MACOSX_DEPLOYMENT_TARGET
is
178 "You cannot safely change the cxx_level after setting it!", stacklevel=2
183 if WIN
and level == 11:
191 cflags = [STD_TMPL.format(level)]
194 if MACOS
and "MACOSX_DEPLOYMENT_TARGET" not in os.environ:
200 current_macos =
tuple(int(x)
for x
in platform.mac_ver()[0].split(
".")[:2])
201 desired_macos = (10, 9)
if level < 17
else (10, 14)
202 macos_string =
".".join(
str(x)
for x
in min(current_macos, desired_macos))
203 macosx_min = f
"-mmacosx-version-min={macos_string}"
204 cflags += [macosx_min]
205 ldflags += [macosx_min]
212tmp_chdir_lock = threading.Lock()
215@contextlib.contextmanager
217 "Prepare and enter a temporary directory, cleanup when done"
223 tmpdir = tempfile.mkdtemp()
228 shutil.rmtree(tmpdir)
234 Return the flag if a flag name
is supported on the
235 specified compiler, otherwise
None (can be used
as a boolean).
236 If multiple flags are passed,
return the first that matches.
240 fname = Path(
"flagcheck.cpp")
242 fname.write_text(
"int main (int, char **) { return 0; }", encoding=
"utf-8")
245 compiler.compile([
str(fname)], extra_postargs=[flag])
246 except distutils.errors.CompileError:
258 Return the max supported C++ std level (17, 14, or 11). Returns latest on Windows.
264 levels = [17, 14, 11]
267 if has_flag(compiler, STD_TMPL.format(level)):
270 msg =
"Unsupported compiler -- at least C++11 support is needed!"
271 raise RuntimeError(msg)
276 Customized build_ext that allows an auto-search for the highest supported
277 C++ level
for Pybind11Extension. This
is only needed
for the auto-search
278 for now,
and is completely optional otherwise.
283 Build extensions, injecting C++ std for Pybind11Extension
if needed.
286 for ext
in self.extensions:
287 if hasattr(ext,
"_cxx_level")
and ext._cxx_level == 0:
294 paths: Iterable[str], package_dir: Optional[Dict[str, str]] =
None
295) -> List[Pybind11Extension]:
297 Generate Pybind11Extensions from source files directly located
in a Python
300 ``package_dir`` behaves
as in ``setuptools.setup``. If unset, the Python
301 package root parent
is determined
as the first parent directory that does
302 not contain an ``__init__.py`` file.
306 if package_dir
is None:
308 parent, _ = os.path.split(path)
309 while os.path.exists(os.path.join(parent,
"__init__.py")):
310 parent, _ = os.path.split(parent)
311 relname, _ = os.path.splitext(os.path.relpath(path, parent))
312 qualified_name = relname.replace(os.path.sep,
".")
317 for prefix, parent
in package_dir.items():
318 if path.startswith(parent):
319 relname, _ = os.path.splitext(os.path.relpath(path, parent))
320 qualified_name = relname.replace(os.path.sep,
".")
322 qualified_name = prefix +
"." + qualified_name
327 f
"path {path} is not a child of any of the directories listed "
328 f
"in 'package_dir' ({package_dir})"
330 raise ValueError(msg)
337 This will recompile only if the source file changes. It does
not check
338 header files, so a more advanced function
or Ccache
is better
if you have
339 editable header files
in your package.
341 return os.stat(obj).st_mtime < os.stat(src).st_mtime
346 This is the safest but slowest choice (
and is the default) - will always
352S = TypeVar(
"S", bound=
"ParallelCompile")
354CCompilerMethod = Callable[
356 distutils.ccompiler.CCompiler,
359 Optional[Union[Tuple[str], Tuple[str, Optional[str]]]],
377 Make a parallel compile function. Inspired by
378 numpy.distutils.ccompiler.CCompiler.compile and cppimport.
380 This takes several arguments that allow you to customize the compile
384 Set an environment variable to control the compilation threads, like
387 0 will automatically multithread,
or 1 will only multithread
if the
390 The limit
for automatic multithreading
if non-zero
392 A function of (obj, src) that returns
True when recompile
is needed. No
393 effect
in isolated mode; use ccache instead, see
394 https://github.com/matplotlib/matplotlib/issues/1507/
405 By default, this assumes all files need to be recompiled. A smarter
406 function can be provided via needs_recompile. If the output has
not yet
407 been generated, the compile will always run,
and this function
is not
411 __slots__ = ("envvar",
"default",
"max",
"_old",
"needs_recompile")
415 envvar: Optional[str] =
None,
418 needs_recompile: Callable[[str, str], bool] = no_recompile,
424 self.
_old: List[CCompilerMethod] = []
428 Builds a function object usable as distutils.ccompiler.CCompiler.compile.
431 def compile_function(
432 compiler: distutils.ccompiler.CCompiler,
434 output_dir: Optional[str] =
None,
435 macros: Optional[Union[Tuple[str], Tuple[str, Optional[str]]]] =
None,
436 include_dirs: Optional[List[str]] =
None,
438 extra_preargs: Optional[List[str]] =
None,
439 extra_postargs: Optional[List[str]] =
None,
440 depends: Optional[List[str]] =
None,
443 macros, objects, extra_postargs, pp_opts, build = compiler._setup_compile(
444 output_dir, macros, include_dirs, sources, depends, extra_postargs
446 cc_args = compiler._get_cc_args(pp_opts, debug, extra_preargs)
452 if self.
envvar is not None:
455 def _single_compile(obj: Any) ->
None:
457 src, ext = build[obj]
462 compiler._compile(obj, src, ext, cc_args, extra_postargs, pp_opts)
467 import multiprocessing.synchronize
468 from multiprocessing.pool
import ThreadPool
474 threads = multiprocessing.cpu_count()
475 threads = self.
max if self.
max and self.
max < threads
else threads
476 except NotImplementedError:
480 with ThreadPool(threads)
as pool:
481 for _
in pool.imap_unordered(_single_compile, objects):
489 return compile_function
493 Installs the compile function into distutils.ccompiler.CCompiler.compile.
499 self.
_old.append(distutils.ccompiler.CCompiler.compile)
503 distutils.ccompiler.CCompiler.compile = self.
_old.pop()
CCompilerMethod function(self)
def __init__(self, envvar=None, default=0, max=0, needs_recompile=no_recompile)
def __exit__(self, *args)
def __init__(self, *args, **kwargs)
def _add_ldflags(self, flags)
def _add_cflags(self, flags)
None _add_cflags(self, List[str] flags)
None cxx_std(self, int level)
None _add_ldflags(self, List[str] flags)
def build_extensions(self)
bool hasattr(handle obj, handle name)
def no_recompile(obg, src)
def intree_extensions(paths, package_dir=None)
def naive_recompile(obj, src)
def auto_cpp_level(compiler)
def has_flag(compiler, flag)