From 7912e3138eed89b39c574b16bc5c7d9c47b1c25e Mon Sep 17 00:00:00 2001 From: Sylvain Corlay Date: Sat, 2 Apr 2016 20:52:46 -0400 Subject: [PATCH] Use -std=c++14 flag when available on clang and gcc --- setup.py | 35 +++++++++++++++++++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/setup.py b/setup.py index 2cebfae..ebb3f1c 100644 --- a/setup.py +++ b/setup.py @@ -1,6 +1,6 @@ from setuptools import setup, Extension from setuptools.command.build_ext import build_ext -import sys +import os, sys ext_modules = [ Extension( @@ -11,12 +11,41 @@ ext_modules = [ ), ] +def has_flag(compiler, flagname): + """Return a boolean indicating whether a flag name is supported on + the specified compiler. + """ + import tempfile + fd, fname = tempfile.mkstemp('.cpp', 'main', text=True) + f = os.fdopen(fd, 'w') + try: + f.write('int main (int argc, char **argv) { return 0; }') + finally: + f.close() + try: + compiler.compile([fname], extra_postargs=[flagname]) + except setuptools.distutils.errors.CompileError: + return False + return True + +def cpp_flag(compiler): + """Return the -std=c++[11/14] compiler flag. + + The c++14 is prefered over c++11 (when it is available). + """ + if has_flag(compiler, '-std=c++14'): + return '-std=c++14' + elif has_flag(compiler, '-std=c++11'): + return '-std=c++11' + else: + raise RuntimeError('Unsupported compiler -- at least C++11 support is needed!') + class BuildExt(build_ext): """A custom build extension for adding compiler-specific options.""" c_opts = { 'msvc': ['/EHsc'], - 'unix': ['-std=c++11'], + 'unix': [], } if sys.platform == 'darwin': @@ -25,6 +54,8 @@ class BuildExt(build_ext): def build_extensions(self): ct = self.compiler.compiler_type opts = self.c_opts.get(ct, []) + if ct == 'unix': + opts.append(cpp_flag(self.compiler)) for ext in self.extensions: ext.extra_compile_args = opts build_ext.build_extensions(self)