Ejemplo n.º 1
0
    def __init__(self, platform=None, **kwargs):
        SConsEnvironment.__init__(self, platform=platform, tools=[])

        self._targets = []

        ### our build process requires that we run everything from the top level dir
        self.SConscriptChdir(False)

        ### extract our specific command line variables
        commandLineOptions = self.getCommandLineOptions()

        ### set the arch and compiler independent options, overriding
        ### defauls with values specified on the command line

        setBaseVars(self, commandLineOptions)

        ### now load the architecture specific defaults
        Arch.updateEnv(self)

        ### should allow for a mechanism for user to override
        ### architecture specific defaults. currently we can only
        ### handle specification of the compiler

        ### since our build paths depend on the arch/compiler settings
        ### we can only set these paths now

        setVersionPaths(self)

        ### keep the sconsign database local to each build rather
        ### than polluting the source tree
        self.SConsignFile('$BUILDVERSIONDIR/sconsign')

        ### for emacs compile mode
        SCons.Util.display("scons: Entering directory `%s'" % os.getcwd())
Ejemplo n.º 2
0
    def __init__(self, platform=None, **kwargs):
        SConsEnvironment.__init__(self, platform=platform, tools=[])

        self._targets = []

        ### our build process requires that we run everything from the top level dir
        self.SConscriptChdir(False)

        ### extract our specific command line variables
        commandLineOptions = self.getCommandLineOptions()

        ### set the arch and compiler independent options, overriding
        ### defauls with values specified on the command line

        setBaseVars(self,commandLineOptions)

        ### now load the architecture specific defaults
        Arch.updateEnv(self)

        ### should allow for a mechanism for user to override
        ### architecture specific defaults. currently we can only
        ### handle specification of the compiler


        ### since our build paths depend on the arch/compiler settings
        ### we can only set these paths now

        setVersionPaths(self)

        ### keep the sconsign database local to each build rather
        ### than polluting the source tree
        self.SConsignFile('$BUILDVERSIONDIR/sconsign')

        ### for emacs compile mode
        SCons.Util.display("scons: Entering directory `%s'" %  os.getcwd())
Ejemplo n.º 3
0
 def BlenderProg(self=None, builddir=None, progname=None, sources=None, libs=None, libpath=None, binarykind=''):
     global vcp
     print bc.HEADER+'Configuring program '+bc.ENDC+bc.OKGREEN+progname+bc.ENDC
     lenv = self.Clone()
     lenv.Append(LINKFLAGS = lenv['PLATFORM_LINKFLAGS'])
     if lenv['OURPLATFORM'] in ('win32-vc', 'cygwin', 'win64-vc'):
         if lenv['BF_DEBUG']:
             lenv.Prepend(LINKFLAGS = ['/DEBUG','/PDB:'+progname+'.pdb','/NODEFAULTLIB:libcmt'])
     if  lenv['OURPLATFORM']=='linux':
         if lenv['WITH_BF_PYTHON']:
             lenv.Append(LINKFLAGS = lenv['BF_PYTHON_LINKFLAGS'])
     if  lenv['OURPLATFORM']=='sunos5':
         if lenv['WITH_BF_PYTHON']:
             lenv.Append(LINKFLAGS = lenv['BF_PYTHON_LINKFLAGS'])
         if lenv['CXX'].endswith('CC'):
              lenv.Replace(LINK = '$CXX')
     if  lenv['OURPLATFORM']=='darwin':
         if lenv['WITH_BF_PYTHON']:
             lenv.Append(LINKFLAGS = lenv['BF_PYTHON_LINKFLAGS'])
         lenv.Append(LINKFLAGS = lenv['BF_OPENGL_LINKFLAGS'])
     if lenv['BF_PROFILE']:
         lenv.Append(LINKFLAGS = lenv['BF_PROFILE_LINKFLAGS'])
     if root_build_dir[0]==os.sep or root_build_dir[1]==':':
         lenv.Append(LIBPATH=root_build_dir + '/lib')
     lenv.Append(LIBPATH=libpath)
     lenv.Append(LIBS=libs)
     if lenv['WITH_BF_QUICKTIME']:
          lenv.Append(LIBS = lenv['BF_QUICKTIME_LIB'])
          lenv.Append(LIBPATH = lenv['BF_QUICKTIME_LIBPATH'])
     prog = lenv.Program(target=builddir+'bin/'+progname, source=sources)
     if lenv['BF_DEBUG'] and lenv['OURPLATFORM'] in ('win32-vc', 'win64-vc') and lenv['BF_BSC']:
         f = lenv.File(progname + '.bsc', builddir)
         brs = lenv.Command(f, prog, [bsc])
         SConsEnvironment.Default(self, brs)
     SConsEnvironment.Default(self, prog)
     if self['BF_MSVS'] and self['OURPLATFORM'] in ('win32-vc', 'win64-vc') and progname == 'blender':
         print "! ",builddir + "/" + progname + '.sln'
         sln = self.MSVSProject(target = builddir + "/" + progname + '.sln',
                  projects= vcp,
                  variant = 'Release')
         SConsEnvironment.Default(self, sln)
     program_list.append(prog)
     if  lenv['OURPLATFORM']=='darwin':
         lenv['BINARYKIND'] = binarykind
         lenv.AddPostAction(prog,Action(AppIt,strfunction=my_appit_print))
     elif os.sep == '/' and lenv['OURPLATFORM'] != 'linuxcross': # any unix (except cross-compilation)
         if lenv['WITH_BF_PYTHON']:
             if not lenv['WITHOUT_BF_INSTALL'] and not lenv['WITHOUT_BF_PYTHON_INSTALL'] and not BlenderEnvironment.PyBundleActionAdded:
                 lenv.AddPostAction(prog,Action(UnixPyBundle,strfunction=my_unixpybundle_print))
                 BlenderEnvironment.PyBundleActionAdded = True
     elif lenv['OURPLATFORM'].startswith('win') or lenv['OURPLATFORM'] == 'linuxcross': # windows or cross-compilation
         if lenv['WITH_BF_PYTHON']:
             if not lenv['WITHOUT_BF_PYTHON_INSTALL'] and not BlenderEnvironment.PyBundleActionAdded:
                 lenv.AddPostAction(prog,Action(WinPyBundle,strfunction=my_winpybundle_print))
                 BlenderEnvironment.PyBundleActionAdded = True
     return prog
Ejemplo n.º 4
0
    def __init__(
        self,
        _platform=None,
        _tools=None,
        toolpath=None,
        variables=None,
        parse_flags=None,
        **kw
    ):
        """Create a new BaseEnvironment instance."""

        if _tools is None:
            toolset = kw.setdefault('ARGUMENTS', {}).get('toolset', os.environ.get('FREELAN_TOOLSET', 'default'))
            _tools = [toolset, 'astyle', 'doxygen', 'nsis', 'innosetup']

        if toolpath is None:
            toolpath = [os.path.abspath(os.path.dirname(__file__))]

        self.arch = kw.setdefault('ARGUMENTS', {}).get('arch', os.environ.get('FREELAN_ARCH', platform.machine()))

        kw.setdefault('TARGET_ARCH', self.arch)

        SConsEnvironment.__init__(
            self,
            _platform,
            _tools,
            toolpath,
            variables,
            parse_flags,
            **kw
        )

        self.mode = kw.setdefault('ARGUMENTS', {}).get('mode', os.environ.get('FREELAN_MODE', 'release'))
        self.bindir = kw.setdefault('ARGUMENTS', {}).get('bindir', os.environ.get('FREELAN_BINDIR', 'bin'))
        self.libdir = kw.setdefault('ARGUMENTS', {}).get('libdir', os.environ.get('FREELAN_LIBDIR', 'lib'))
        self.static_suffix = kw.setdefault('ARGUMENTS', {}).get('static_suffix', os.environ.get('FREELAN_STATIC_SUFFIX', '_static'))

        if not self.mode in ['release', 'debug']:
            raise ValueError('\"mode\" can be either \"release\" or \"debug\"')

        # Parse environment overloads
        if 'ENV' in kw:
            for key, value in kw['ENV'].items():
                if key.startswith('FREELAN_ENV_'):
                    self[key[len('FREELAN_ENV_'):]] = value

        if not 'CXXFLAGS' in self:
            self['CXXFLAGS'] = []

        if not 'LINKFLAGS' in self:
            self['LINKFLAGS'] = []

        if not 'SHLINKFLAGS' in self:
            self['SHLINKFLAGS'] = []
Ejemplo n.º 5
0
 def myClone(self, newTargets=False):
     newEnv = SConsEnvironment.Clone(self)
     if newTargets:
         newEnv._targets = []
     else:
         newEnv._targets = self._targets
     return newEnv
Ejemplo n.º 6
0
    def __init__(self, **kwargs):
        try:
            tools = list(kwargs.pop("tools"))
            tools.append('packaging')
        except KeyError:
            tools = ['default', 'packaging']

        # omero_quiet is for internal use in order to
        # quiet down this instance for re-use.
        try:
            self.omero_quiet = kwargs.pop("omero_quiet")
        except KeyError:
            self.omero_quiet = False

        # Very odd error: using ENV = os.environ, rather than
        # ENV = dict(os.environ) causes *sub*processes to receive a fresh
        # environment with registry values for PATH, LIB, etc. *pre*pended to
        # the variables.
        SConsEnvironment.__init__(self, ENV=dict(os.environ), tools=tools,
                                  **kwargs)
        self.Decider('MD5-timestamp')
Ejemplo n.º 7
0
    def __init__(self, **kwargs):
        try:
            tools = list(kwargs.pop("tools"))
            tools.append('packaging')
        except KeyError:
            tools = ['default', 'packaging']

        # omero_quiet is for internal use in order to
        # quiet down this instance for re-use.
        try:
            self.omero_quiet = kwargs.pop("omero_quiet")
        except KeyError:
            self.omero_quiet = False

        # Very odd error: using ENV = os.environ, rather than
        # ENV = dict(os.environ) causes *sub*processes to receive a fresh
        # environment with registry values for PATH, LIB, etc. *pre*pended to
        # the variables.
        SConsEnvironment.__init__(self,
                                  ENV=dict(os.environ),
                                  tools=tools,
                                  **kwargs)
        self.Decider('MD5-timestamp')
Ejemplo n.º 8
0
    def BlenderRes(self=None, libname=None, source=None, libtype=['core'], priority=[100]):
        global libs
        if not self or not libname or not source:
            print bc.FAIL+'Cannot continue.  Missing argument for BlenderRes '+libname+bc.ENDC
            self.Exit()
        if self['OURPLATFORM'] not in ('win32-vc','win32-mingw','linuxcross', 'win64-vc', 'win64-mingw'):
            print bc.FAIL+'BlenderRes is for windows only!'+bc.END
            self.Exit()
        
        print bc.HEADER+'Configuring resource '+bc.ENDC+bc.OKGREEN+libname+bc.ENDC
        lenv = self.Clone()
        if not (root_build_dir[0]==os.sep or root_build_dir[1]==':'):
            res = lenv.RES('#'+root_build_dir+'lib/'+libname, source)
        else:
            res = lenv.RES(root_build_dir+'lib/'+libname, source)

        
        SConsEnvironment.Default(self, res)
        resources.append(res)
Ejemplo n.º 9
0
    def BlenderLib(self=None,
                   libname=None,
                   sources=None,
                   includes=[],
                   defines=[],
                   libtype='common',
                   priority=100,
                   compileflags=None,
                   cc_compileflags=None,
                   cxx_compileflags=None,
                   cc_compilerchange=None,
                   cxx_compilerchange=None):
        global vcp

        # sanity check
        # run once in a while to check we dont have duplicates
        if 0:
            for name, dirs in (("source", sources), ("include", includes)):
                files_clean = [os.path.normpath(f) for f in dirs]
                files_clean_set = set(files_clean)
                if len(files_clean) != len(files_clean_set):
                    for f in sorted(files_clean_set):
                        if f != '.' and files_clean.count(f) > 1:
                            raise Exception("Found duplicate %s %r" %
                                            (name, f))
            del name, dirs, files_clean, files_clean_set, f
        # end sanity check

        if not self or not libname or not sources:
            print bc.FAIL + 'Cannot continue. Missing argument for BuildBlenderLib ' + libname + bc.ENDC
            self.Exit()

        def list_substring(quickie, libname):
            for q in quickie:
                if q in libname:
                    return True
            return False

        if list_substring(quickie, libname) or len(quickie) == 0:
            if list_substring(quickdebug, libname):
                print bc.HEADER + 'Configuring library ' + bc.ENDC + bc.OKGREEN + libname + bc.ENDC + bc.OKBLUE + " (debug mode)" + bc.ENDC
            else:
                print bc.HEADER + 'Configuring library ' + bc.ENDC + bc.OKGREEN + libname + bc.ENDC
            lenv = self.Clone()
            lenv.Append(CPPPATH=includes)
            lenv.Append(CPPDEFINES=defines)
            if lenv['BF_DEBUG'] or (libname in quickdebug):
                lenv.Append(CFLAGS=lenv['BF_DEBUG_CFLAGS'])
                lenv.Append(CCFLAGS=lenv['BF_DEBUG_CCFLAGS'])
                lenv.Append(CXXFLAGS=lenv['BF_DEBUG_CXXFLAGS'])
            else:
                lenv.Append(CFLAGS=lenv['REL_CFLAGS'])
                lenv.Append(CCFLAGS=lenv['REL_CCFLAGS'])
                lenv.Append(CXXFLAGS=lenv['REL_CXXFLAGS'])
            if lenv['BF_PROFILE']:
                lenv.Append(CFLAGS=lenv['BF_PROFILE_CFLAGS'])
                lenv.Append(CCFLAGS=lenv['BF_PROFILE_CCFLAGS'])
                lenv.Append(CXXFLAGS=lenv['BF_PROFILE_CXXFLAGS'])
            if compileflags:
                lenv.Replace(CFLAGS=compileflags)
            if cc_compileflags:
                lenv.Replace(CCFLAGS=cc_compileflags)
            if cxx_compileflags:
                lenv.Replace(CXXFLAGS=cxx_compileflags)
            if cc_compilerchange:
                lenv.Replace(CC=cc_compilerchange)
            if cxx_compilerchange:
                lenv.Replace(CXX=cxx_compilerchange)
            lenv.Append(CFLAGS=lenv['C_WARN'])
            lenv.Append(CCFLAGS=lenv['CC_WARN'])
            lenv.Append(CXXFLAGS=lenv['CXX_WARN'])

            if lenv['OURPLATFORM'] == 'win64-vc':
                lenv.Append(LINKFLAGS=['/MACHINE:X64'])

            if lenv['OURPLATFORM'] in ('win32-vc', 'win64-vc'):
                if lenv['BF_DEBUG']:
                    lenv.Append(CCFLAGS=['/MTd'])
                else:
                    lenv.Append(CCFLAGS=['/MT'])

            targetdir = root_build_dir + 'lib/' + libname
            if not (root_build_dir[0] == os.sep or root_build_dir[1] == ':'):
                targetdir = '#' + targetdir
            lib = lenv.Library(target=targetdir, source=sources)
            SConsEnvironment.Default(
                self, lib
            )  # we add to default target, because this way we get some kind of progress info during build
            if self['BF_MSVS'] and self['OURPLATFORM'] in ('win32-vc',
                                                           'win64-vc'):
                #if targetdir[0] == '#':
                #    targetdir = targetdir[1:-1]
                print "! ", targetdir + '.vcproj'  # + self['MSVSPROJECTSUFFIX']
                vcproject = self.MSVSProject(
                    target=targetdir +
                    '.vcproj',  # + self['MSVSPROJECTSUFFIX'],
                    srcs=sources,
                    buildtarget=lib,
                    variant='Release',
                    auto_build_solution=0)
                vcp.append(vcproject)
                SConsEnvironment.Default(self, vcproject)
        else:
            print bc.WARNING + 'Not building ' + bc.ENDC + bc.OKGREEN + libname + bc.ENDC + ' for ' + bc.OKBLUE + 'BF_QUICK' + bc.ENDC
        # note: libs is a global
        add_lib_to_dict(self, libs, libtype, libname, priority)
Ejemplo n.º 10
0
def doConfigure(env, moduleFolders, languageWrapperFolders):
    print "Checking programs and libraries: "

    config = env.Configure(
        custom_tests={
            'CheckExec': SGppConfigureExtend.CheckExec,
            'CheckJNI': SGppConfigureExtend.CheckJNI,
            'CheckFlag': SGppConfigureExtend.CheckFlag
        })

    # check C++11 support
    if not config.CheckFlag("-std=c++11"):
        sys.stderr.write(
            "Error: compiler doesn't seem to support the C++11 standard. Abort!\n"
        )
        sys.exit(1)  # TODO: exist undefined, fix

    config.env.AppendUnique(CPPFLAGS="-std=c++11")

    # boost library
    #TODO: add check and error
    config.env.AppendUnique(CPPPATH=[config.env['BOOST_INCLUDE_PATH']])
    config.env.AppendUnique(LIBPATH=[config.env['BOOST_LIBRARY_PATH']])

    # check whether swig installed
    if not config.CheckExec('doxygen'):
        sys.stderr.write(
            "Warning: doxygen cannot be found.\n  You will not be able to generate the documentation.\n  Check PATH environment variable!\n"
        )
    else:
        print "Using doxygen " + re.findall(
            r"[0-9.]*[0-9]+", subprocess.check_output(['doxygen', '--version'
                                                       ]))[0]

    # check whether dot installed
    if not config.CheckExec('dot'):
        sys.stderr.write(
            "Warning: dot (Graphviz) cannot be found.\n  The documentation might lack diagrams.\n  Check PATH environment variable!\n"
        )
    else:
        print subprocess.check_output(['dot', '-V'])

    if config.env['USE_OCL']:
        if 'OCL_INCLUDE_PATH' in config.env['ENV']:
            config.env.AppendUnique(
                CPPPATH=[config.env['ENV']['OCL_INCLUDE_PATH']])
        elif 'OCL_INCLUDE_PATH' in config.env:
            config.env.AppendUnique(CPPPATH=[config.env['OCL_INCLUDE_PATH']])
        else:
            sys.stderr.write(
                "Info: Trying to find the OpenCL without the variable \"OCL_INCLUDE_PATH\"\n"
            )

        if not config.CheckCXXHeader('CL/cl.h'):
            sys.stderr.write(
                "Error: \"CL/cl.h\" not found, but required for OpenCL\n")
            sys.exit(1)

        if 'OCL_LIBRARY_PATH' in config.env['ENV']:
            config.env.AppendUnique(
                LIBPATH=[config.env['ENV']['OCL_LIBRARY_PATH']])
        elif 'OCL_LIBRARY_PATH' in config.env:
            config.env.AppendUnique(LIBPATH=[config.env['OCL_LIBRARY_PATH']])
        else:
            sys.stderr.write(
                "Info: Trying to find the OpenCL library \"libOpenCL\" without the variable \"OCL_LIBRARY_PATH\"\n"
            )

        if not config.CheckLib('OpenCL', language="c++", autoadd=1):
            sys.stderr.write(
                "Error: \"libOpenCL\" not found, but required for OpenCL\n")
            sys.exit(1)

        if not config.CheckLib(
                'boost_program_options', language="c++", autoadd=0):
            sys.stderr.write(
                "Error: \"libboost-program-options\" not found, but required for OpenCL\n"
            )
            sys.stderr.write(
                "On debian-like system the package \"libboost-program-options-dev\" can be installed to solve this issue\n"
            )
            sys.exit(1)

        config.env["CPPDEFINES"]["USE_OCL"] = "1"
    else:
        print "Info: OpenCL is not enabled"

    # Check the availability of the boost unit test dependencies
    if env['COMPILE_BOOST_TESTS']:
        if not config.CheckHeader(os.path.join("boost", "test",
                                               "unit_test.hpp"),
                                  language="c++"):
            env['COMPILE_BOOST_TESTS'] = False
            print """****************************************************
No Boost Unit Test Headers found. Omitting Boost unit tests.
Please install the corresponding package, e.g. using command on Ubuntu
> sudo apt-get install libboost-test-dev
****************************************************
"""

        if not config.CheckLib(
                'boost_unit_test_framework', autoadd=0, language="c++"):
            env['COMPILE_BOOST_TESTS'] = False
            print """****************************************************
No Boost Unit Test library found. Omitting Boost unit tests.
Please install the corresponding package, e.g. using command on Ubuntu
> sudo apt-get install libboost-test-dev
****************************************************
"""

    if env["SG_PYTHON"]:
        # check whether swig installed
        if not config.CheckExec('swig'):
            sys.stderr.write(
                "Error: swig cannot be found, but required for SG_PYTHON. Check PATH environment variable!\n"
            )
            sys.exit(1)

        # make sure swig version is new enough
        from SCons.Script.SConscript import SConsEnvironment
        import warnings
        sconsenv = SConsEnvironment()
        swig_ver = sconsenv._get_major_minor_revision(
            re.findall(r"[0-9.]*[0-9]+",
                       subprocess.check_output(['swig', '-version']))[0])
        if swig_ver < (3, 0, 0):
            sys.stderr.write(
                "Error: swig version too old! Use swig >= 3.0.0\n")
            sys.exit(1)

        print "Using SWIG " + re.findall(
            r"[0-9.]*[0-9]+", subprocess.check_output(['swig', '-version']))[0]
        config.env.AppendUnique(CPPPATH=[distutils.sysconfig.get_python_inc()])
        print "pythonpath: ", distutils.sysconfig.get_python_inc()

        if not config.CheckCXXHeader('Python.h'):
            sys.stderr.write(
                "Error: Python.h not found, but required for SG_PYTHON. Check path to Python include files: "
                + distutils.sysconfig.get_python_inc() + "\n")
            sys.stderr.write(
                "Hint: You might have to install package python-dev\n")
            sys.exit(1)

        if not config.CheckCXXHeader('pyconfig.h'):
            sys.stderr.write(
                "Error: pyconfig.h not found, but required for SG_PYTHON. Check path to Python include files: "
                + distutils.sysconfig.get_python_inc() + "\n")
            sys.stderr.write(
                "Hint: You might have to install package python-dev\n")
            sys.exit(1)

        try:
            import numpy
            numpy_path = os.path.join(
                os.path.split(numpy.__file__)[0], "core", "include")
            config.env.AppendUnique(CPPPATH=[numpy_path])
            if not config.CheckCXXHeader(
                ['Python.h', 'pyconfig.h', 'numpy/arrayobject.h']):
                sys.stderr.write(
                    'Warning: Cannot find NumPy header files in: "' +
                    str(numpy_path) + '", disabling unit tests\n')
                env['NO_UNIT_TESTS'] = True
        except:
            sys.stderr.write(
                'Warning: Numpy doesn\'t seem to be installed. Disabling unit tests\n'
            )
            env['NO_UNIT_TESTS'] = True
    else:
        print 'Warning: Python extension ("SG_PYTHON") not enabled, skipping python unit tests'

    if env['SG_JAVA']:
        # check for $JAVA_HOME; prepend to search path
        if os.environ.get('JAVA_HOME'):
            config.env.PrependENVPath(
                'PATH', os.path.join(os.environ.get('JAVA_HOME'), 'bin'))
        # check whether javac installed
        if not config.CheckExec('javac'):
            sys.stderr.write(
                "Error: javac cannot be found, but required by SG_JAVA. Check PATH environment variable!\n"
            )
            sys.exit(1)
        # check whether javac installed
        if not config.CheckExec('java'):
            sys.stderr.write(
                "Warning: java cannot be found, but required by SG_JAVA. Check PATH environment variable!\n"
            )
            sys.exit(1)

        # check for JNI headers
        if os.environ.get('JNI_CPPINCLUDE'):
            config.env.AppendUnique(CPPPATH=[os.environ.get('JNI_CPPINCLUDE')])
        if not config.CheckCXXHeader('jni.h'):
            # not found; try to find
            if not config.CheckJNI():
                sys.stderr.write(
                    "Error: jni.h not found.\n" +
                    "Please set JAVA_HOME environment variable " +
                    "with $JAVA_HOME/bin/javac, $JAVA_HOME/include/jni.h\n" +
                    "or directly $JNI_CPPINCLUDE with $JNI_CPPINCLUDE/jni.h\n")
                sys.exit(1)
    else:
        print 'Warning: Java support ("SG_JAVA") not enabled.'

    # now set up all further environment settings that should never fail
    # compiler setup should be always after checking headers and flags, as they can make the checks invalid
    # e.g. by setting "-Werror"

    # TODO check
    if env['PLATFORM'] not in ['cygwin', 'win32']:
        if env['OPT'] == True:
            env.Append(CPPFLAGS=['-O3', '-g'])
        else:
            env.Append(CPPFLAGS=['-g', '-O0'])

    if not env['USE_DOUBLE_PRECISION']:
        env.Append(CPPFLAGS=['-DUSE_DOUBLE_PRECISION=0'])

    # make settings case-insensitive
    env['COMPILER'] = env['COMPILER'].lower()
    env['ARCH'] = env['ARCH'].lower()

    if env['COMPILER'] == 'gnu':
        gcc_ver_str = subprocess.check_output([env['CXX'], '-dumpversion'])
        gcc_ver = env._get_major_minor_revision(gcc_ver_str)
        print "Using default gcc " + gcc_ver_str

        allWarnings = "-Wall -pedantic -pedantic-errors -Wextra \
            -Wcast-align -Wcast-qual -Wconversion -Wdisabled-optimization -Wformat=2 \
            -Wformat-nonliteral -Wformat-security -Wformat-y2k -Wimport  -Winit-self  \
            -Winvalid-pch -Wmissing-field-initializers -Wmissing-format-attribute -Wmissing-include-dirs \
             -Wpacked   -Wpointer-arith -Wredundant-decls -Wstack-protector \
            -Wstrict-aliasing=2 -Wswitch-default -Wswitch-enum -Wunreachable-code -Wunused -Wunused-parameter \
            -Wvariadic-macros -Wwrite-strings -Wuninitialized".split(" ")
        # rather uninteresting: -Wlong-long -Wpadded -Wshadow -Wfloat-equal -Waggregate-return -Wimplicit -Wmissing-noreturn -Weffc++
        # cannot really use:

        # -fno-strict-aliasing: http://www.swig.org/Doc1.3/Java.html or http://www.swig.org/Release/CHANGES, 03/02/2006
        #    "If you are going to use optimisations turned on with gcc > 4.0 (for example -O2),
        #     ensure you also compile with -fno-strict-aliasing"
        env.Append(CPPFLAGS=allWarnings + [
            '-Wno-unused-parameter', '-fno-strict-aliasing', '-funroll-loops',
            '-mfpmath=sse', '-DDEFAULT_RES_THRESHOLD=-1.0',
            '-DTASKS_PARALLEL_UPDOWN=4'
        ])
        env.Append(CPPFLAGS=['-fopenmp'])
        env.Append(LINKFLAGS=['-fopenmp'])

        # required for profiling
        env.Append(CPPFLAGS=['-fno-omit-frame-pointer'])

        if env['USE_STATICLIB']:
            env.Append(CPPFLAGS=['-D_USE_STATICLIB'])

        if not env['USE_DOUBLE_PRECISION']:
            if gcc_ver >= (4, 9, 0):
                # disable warnings which occur for, e.g., "SGPP::float_t value = 1.0/3.0;"
                # (-Wno-float-conversion was introduced with g++ 4.9)
                env.Append(CPPFLAGS=['-Wno-float-conversion'])
            else:
                # disable all conversion warnings
                env.Append(CPPFLAGS=['-Wno-conversion'])

        if env['ARCH'] == 'sse3':
            config.env.AppendUnique(CPPFLAGS=["-msse3"])
        elif env['ARCH'] == 'sse42':
            config.env.AppendUnique(CPPFLAGS=["-msse4.2"])
        elif env['ARCH'] == 'avx':
            config.env.AppendUnique(CPPFLAGS=["-mavx"])
        elif env['ARCH'] == 'fma4':
            config.env.AppendUnique(CPPFLAGS=["-mavx"])
            config.env.AppendUnique(CPPFLAGS=["-mfma4"])
        elif env['ARCH'] == 'avx2':
            config.env.AppendUnique(CPPFLAGS=["-mavx2"])
            config.env.AppendUnique(CPPFLAGS=["-mfma"])
        elif env['ARCH'] == 'avx512':
            config.env.AppendUnique(CPPFLAGS=["-mavx512f"])
            config.env.AppendUnique(CPPFLAGS=["-mavx512cd"])
            config.env.AppendUnique(CPPFLAGS=["-mfma"])
        else:
            print "You must specify a valid ARCH value for gnu."
            print "Available configurations are: sse3, sse42, avx, fma4, avx2, avx512"
            sys.exit(1)

        # check if using MinGW (g++ on win32)
        if env['PLATFORM'] == 'win32':
            # disable warnings which occur when including Boost in the tests
            env.Append(
                CPPFLAGS=['-Wno-switch-enum', '-Wno-deprecated-declarations'])
            # also use "lib" prefix on MinGW for consistency with Linux
            # (default is no prefix)
            env['SHLIBPREFIX'] = 'lib'
    elif env['COMPILER'] == 'clang':
        print "Using clang"

        env['CC'] = ('clang')
        env['LINK'] = ('clang++')
        env['CXX'] = ('clang++')

        allWarnings = "-Wall -Wextra".split(" ")

        # -fno-strict-aliasing: http://www.swig.org/Doc1.3/Java.html or http://www.swig.org/Release/CHANGES, 03/02/2006
        #    "If you are going to use optimisations turned on with gcc > 4.0 (for example -O2),
        #     ensure you also compile with -fno-strict-aliasing"
        env.Append(
            CPPFLAGS=allWarnings +
            ['-DDEFAULT_RES_THRESHOLD=-1.0', '-DTASKS_PARALLEL_UPDOWN=4'])
        env.Append(CPPFLAGS=['-fopenmp=libomp'])
        env.Append(LINKFLAGS=['-fopenmp=libomp'])

        if env['USE_STATICLIB']:
            env.Append(CPPFLAGS=['-D_USE_STATICLIB'])

        if not env['USE_DOUBLE_PRECISION']:
            if gcc_ver >= (4, 9, 0):
                # disable warnings which occur for, e.g., "SGPP::float_t value = 1.0/3.0;"
                # (-Wno-float-conversion was introduced with g++ 4.9)
                env.Append(CPPFLAGS=['-Wno-float-conversion'])
            else:
                # disable all conversion warnings
                env.Append(CPPFLAGS=['-Wno-conversion'])

        if env['ARCH'] == 'sse3':
            config.env.AppendUnique(CPPFLAGS=["-msse3"])
        elif env['ARCH'] == 'sse42':
            config.env.AppendUnique(CPPFLAGS=["-msse4.2"])
        elif env['ARCH'] == 'avx':
            config.env.AppendUnique(CPPFLAGS=["-mavx"])
        elif env['ARCH'] == 'fma4':
            config.env.AppendUnique(CPPFLAGS=["-mavx"])
            config.env.AppendUnique(CPPFLAGS=["-mfma4"])
        elif env['ARCH'] == 'avx2':
            config.env.AppendUnique(CPPFLAGS=["-mavx2"])
            config.env.AppendUnique(CPPFLAGS=["-mfma"])
        elif env['ARCH'] == 'avx512':
            config.env.AppendUnique(CPPFLAGS=["-mavx512f"])
            config.env.AppendUnique(CPPFLAGS=["-mavx512cd"])
            config.env.AppendUnique(CPPFLAGS=["-mfma"])
        else:
            print "You must specify a valid ARCH value for gnu."
            print "Available configurations are: sse3, sse4.2, avx, fma4, avx2, avx512"
            sys.exit(1)

    elif env['COMPILER'] == 'intel':
        print "Using icc"
        env.AppendUnique(CPPFLAGS=[
            '-Wall', '-ansi', '-Wno-deprecated', '-wd1125',
            '-fno-strict-aliasing', '-ip', '-ipo', '-funroll-loops',
            '-ansi-alias', '-fp-speculation=safe',
            '-DDEFAULT_RES_THRESHOLD=-1.0', '-DTASKS_PARALLEL_UPDOWN=4',
            '-no-offload'
        ])

        env['CC'] = ('icc')
        env['LINK'] = ('icpc')
        env['CXX'] = ('icpc')

        env.AppendUnique(CPPFLAGS=['-openmp'])
        env.AppendUnique(LINKFLAGS=['-openmp'])

        if env['USE_STATICLIB']:
            env.AppendUnique(CPPFLAGS=['-D_USE_STATICLIB'])

        if not env['USE_DOUBLE_PRECISION']:
            if gcc_ver >= (4, 9, 0):
                # disable warnings which occur for, e.g., "SGPP::float_t value = 1.0/3.0;"
                # (-Wno-float-conversion was introduced with g++ 4.9)
                env.AppendUnique(CPPFLAGS=['-Wno-float-conversion'])
            else:
                # disable all conversion warnings
                env.AppendUnique(CPPFLAGS=['-Wno-conversion'])

        if env['ARCH'] == 'sse3':
            config.env.AppendUnique(CPPFLAGS=["-msse3"])
        elif env['ARCH'] == 'sse42':
            config.env.AppendUnique(CPPFLAGS=["-msse4.2"])
        elif env['ARCH'] == 'avx':
            config.env.AppendUnique(CPPFLAGS=["-mavx"])
        elif env['ARCH'] == 'avx2':
            config.env.AppendUnique(CPPFLAGS=["-xCORE-AVX2"])
            config.env.AppendUnique(CPPFLAGS=["-fma"])
        elif env['ARCH'] == 'avx512':
            config.env.AppendUnique(CPPFLAGS=["-xCOMMON-AVX512"])
            config.env.AppendUnique(CPPFLAGS=["-fma"])
        elif env['ARCH'] == 'mic':
            config.env.AppendUnique(CPPFLAGS=["-mmic"])
            config.env.AppendUnique(LINKFLAGS=['-mmic'])
        else:
            print "You must specify a valid ARCH value for intel."
            print "Available configurations are: sse3, sse4.2, avx, avx2, avx512, mic"
            sys.exit(1)

        env.AppendUnique(CPPPATH=[distutils.sysconfig.get_python_inc()])
    else:
        print "You must specify a valid value for Compiler."
        print "Available configurations are: gnu, clang, and intel"
        sys.exit(1)

    # special treatment for different platforms
    if env['PLATFORM'] == 'darwin':
        # the "-undefined dynamic_lookup"-switch is required to actually build a shared library
        # in OSX. "-dynamiclib" alone results in static linking of all further dependent shared libraries
        # beware: if symbols are missing that are actually required (because the symbols don't reside in a shared library), there will be no error during compilation
        # the python binding (pysgpp) requires lpython and a flat namespace
        # also for the python binding, the library must be suffixed with '*.so' even though it is a dynamiclib and not a bundle (see SConscript in src/pysgpp)
        env.AppendUnique(LINKFLAGS=[
            '-flat_namespace', '-undefined', 'dynamic_lookup', '-lpython'
        ])
        # The GNU assembler (GAS) is not supported in Mac OS X. A solution that fixed this problem is by adding -Wa,-q to the compiler flags.
        # From the man pages for as (version 1.38): -q Use the clang(1) integrated assembler instead of the GNU based system assembler.
        # Note that the CPPFLAG is exactly "-Wa,-q", where -Wa passes flags to the assembler and -q is the relevant flag to make it use integrated assembler
        env.AppendUnique(CPPFLAGS=['-Wa,-q'])
        env.AppendUnique(CPPPATH="/usr/local/include")
        env.AppendUnique(LIBPATH="/usr/local/lib")
        env['SHLIBSUFFIX'] = '.dylib'
    elif env['PLATFORM'] == 'cygwin':
        # required to find the static libraries compiled before the shared libraries
        # the static libraries are required as the linker on windows cannot ignore undefined symbols
        # (as is done on linux automatically and is done on OSX with the settings above)
        #env.Append(LIBPATH=[BUILD_DIR])
        pass

    # will lead to a warning on cygwin and win32
    # ("all code is position independent")
    if env['PLATFORM'] not in ['cygwin', 'win32']:
        env.AppendUnique(CPPFLAGS=['-fPIC'])

    # setup the include base folder
    # env.Append(CPPPATH=['#/src/sgpp'])
    for moduleFolder in moduleFolders:
        if (moduleFolder in languageWrapperFolders) or \
            (not env['SG_' + moduleFolder.upper()]):
            continue
        env.AppendUnique(CPPPATH=['#/' + moduleFolder + '/src/'])

    # check for mpic++
    if not env['CXX'] == 'mpic++':
        env['SG_PARALLEL'] = 0
        print 'Hint: not using mpic++, parallel module ("SG_PARALLEL") disabled, since it requires mpic++'
    elif env['SG_PARALLEL'] != 0:
        env['CPPDEFINES']['USE_MPI'] = '1'
        print 'Parallel module ("SG_PARALLEL") enabled'
    else:
        print 'Parallel module ("SG_PARALLEL") disabled'

    # detour compiler output
    env['PRINT_CMD_LINE_FUNC'] = Helper.print_cmd_line

    env = config.Finish()

    # clear build_log file
    with open(env['CMD_LOGFILE'], 'a') as logFile:
        logFile.seek(0)
        logFile.truncate()
Ejemplo n.º 11
0
def doConfigure(env, moduleFolders, languageWrapperFolders):
    print "Checking programs and libraries: "

    config = env.Configure(custom_tests={ 'CheckExec' : SGppConfigureExtend.CheckExec,
                                            'CheckJNI' : SGppConfigureExtend.CheckJNI,
                                            'CheckFlag' : SGppConfigureExtend.CheckFlag })

    # check C++11 support
    if not config.CheckFlag("-std=c++11"):
        sys.stderr.write("Error: compiler doesn't seem to support the C++11 standard. Abort!\n")
        sys.exit(1)  # TODO: exist undefined, fix

    config.env.AppendUnique(CPPFLAGS="-std=c++11")

    # boost library
    #TODO: add check and error
    config.env.AppendUnique(CPPPATH=[config.env['BOOST_INCLUDE_PATH']])
    config.env.AppendUnique(LIBPATH=[config.env['BOOST_LIBRARY_PATH']])


    # check whether swig installed
    if not config.CheckExec('doxygen'):
        sys.stderr.write("Warning: doxygen cannot be found.\n  You will not be able to generate the documentation.\n  Check PATH environment variable!\n")
    else:
        print "Using doxygen " + re.findall(r"[0-9.]*[0-9]+",
                                            subprocess.check_output(['doxygen', '--version']))[0]

    # check whether dot installed
    if not config.CheckExec('dot'):
        sys.stderr.write("Warning: dot (Graphviz) cannot be found.\n  The documentation might lack diagrams.\n  Check PATH environment variable!\n")
    else:
        print subprocess.check_output(['dot', '-V'])

    if config.env['USE_OCL']:
      if 'OCL_INCLUDE_PATH' in config.env['ENV']:
        config.env.AppendUnique(CPPPATH=[config.env['ENV']['OCL_INCLUDE_PATH']])
      elif 'OCL_INCLUDE_PATH' in config.env:
        config.env.AppendUnique(CPPPATH=[config.env['OCL_INCLUDE_PATH']])
      else:
        sys.stderr.write("Info: Trying to find the OpenCL without the variable \"OCL_INCLUDE_PATH\"\n")

      if not config.CheckCXXHeader('CL/cl.h'):
        sys.stderr.write("Error: \"CL/cl.h\" not found, but required for OpenCL\n")
        sys.exit(1)

      if 'OCL_LIBRARY_PATH' in config.env['ENV']:
        config.env.AppendUnique(LIBPATH=[config.env['ENV']['OCL_LIBRARY_PATH']])
      elif 'OCL_LIBRARY_PATH' in config.env:
        config.env.AppendUnique(LIBPATH=[config.env['OCL_LIBRARY_PATH']])
      else:
        sys.stderr.write("Info: Trying to find the OpenCL library \"libOpenCL\" without the variable \"OCL_LIBRARY_PATH\"\n")

      if not config.CheckLib('OpenCL', language="c++", autoadd=1):
        sys.stderr.write("Error: \"libOpenCL\" not found, but required for OpenCL\n")
        sys.exit(1)
        
      if not config.CheckLib('boost_program_options', language="c++", autoadd=0):
        sys.stderr.write("Error: \"libboost-program-options\" not found, but required for OpenCL\n")
        sys.stderr.write("On debian-like system the package \"libboost-program-options-dev\" can be installed to solve this issue\n")
        sys.exit(1)

      config.env["CPPDEFINES"]["USE_OCL"] = "1"
    else:
      print "Info: OpenCL is not enabled"

    # Check the availability of the boost unit test dependencies
    if env['COMPILE_BOOST_TESTS']:
        if not config.CheckHeader(os.path.join("boost", "test", "unit_test.hpp"), language="c++"):
            env['COMPILE_BOOST_TESTS'] = False
            print """****************************************************
No Boost Unit Test Headers found. Omitting Boost unit tests.
Please install the corresponding package, e.g. using command on Ubuntu
> sudo apt-get install libboost-test-dev
****************************************************
"""

        if not config.CheckLib('boost_unit_test_framework', autoadd=0, language="c++"):
            env['COMPILE_BOOST_TESTS'] = False
            print """****************************************************
No Boost Unit Test library found. Omitting Boost unit tests.
Please install the corresponding package, e.g. using command on Ubuntu
> sudo apt-get install libboost-test-dev
****************************************************
"""

    if env["SG_PYTHON"]:
        # check whether swig installed
        if not config.CheckExec('swig'):
            sys.stderr.write("Error: swig cannot be found, but required for SG_PYTHON. Check PATH environment variable!\n")
            sys.exit(1)

        # make sure swig version is new enough
        from SCons.Script.SConscript import SConsEnvironment
        import warnings
        sconsenv = SConsEnvironment()
        swig_ver = sconsenv._get_major_minor_revision(re.findall(r"[0-9.]*[0-9]+",
                                                      subprocess.check_output(['swig', '-version']))[0])
        if swig_ver < (3, 0, 0):
          sys.stderr.write("Error: swig version too old! Use swig >= 3.0.0\n")
          sys.exit(1)

        print "Using SWIG " + re.findall(r"[0-9.]*[0-9]+",
                                         subprocess.check_output(['swig', '-version']))[0]
        config.env.AppendUnique(CPPPATH=[distutils.sysconfig.get_python_inc()])
        print "pythonpath: ", distutils.sysconfig.get_python_inc()

        if not config.CheckCXXHeader('Python.h'):
            sys.stderr.write("Error: Python.h not found, but required for SG_PYTHON. Check path to Python include files: "
                         + distutils.sysconfig.get_python_inc() + "\n")
            sys.stderr.write("Hint: You might have to install package python-dev\n")
            sys.exit(1)

        if not config.CheckCXXHeader('pyconfig.h'):
            sys.stderr.write("Error: pyconfig.h not found, but required for SG_PYTHON. Check path to Python include files: "
                         + distutils.sysconfig.get_python_inc() + "\n")
            sys.stderr.write("Hint: You might have to install package python-dev\n")
            sys.exit(1)

        try:
            import numpy
            numpy_path = os.path.join(os.path.split(numpy.__file__)[0], "core", "include")
            config.env.AppendUnique(CPPPATH=[numpy_path])
            if not config.CheckCXXHeader(['Python.h', 'pyconfig.h', 'numpy/arrayobject.h']):
                sys.stderr.write('Warning: Cannot find NumPy header files in: "' + str(numpy_path) + '", disabling unit tests\n')
                env['NO_UNIT_TESTS'] = True
        except:
            sys.stderr.write('Warning: Numpy doesn\'t seem to be installed. Disabling unit tests\n')
            env['NO_UNIT_TESTS'] = True
    else:
        print 'Warning: Python extension ("SG_PYTHON") not enabled, skipping python unit tests'

    if env['SG_JAVA']:
        # check for $JAVA_HOME; prepend to search path
        if os.environ.get('JAVA_HOME'):
            config.env.PrependENVPath('PATH', os.path.join(os.environ.get('JAVA_HOME'), 'bin'))
        # check whether javac installed
        if not config.CheckExec('javac'):
            sys.stderr.write("Error: javac cannot be found, but required by SG_JAVA. Check PATH environment variable!\n")
            sys.exit(1)
        # check whether javac installed
        if not config.CheckExec('java'):
            sys.stderr.write("Warning: java cannot be found, but required by SG_JAVA. Check PATH environment variable!\n")
            sys.exit(1)

        # check for JNI headers
        if os.environ.get('JNI_CPPINCLUDE'):
            config.env.AppendUnique(CPPPATH=[os.environ.get('JNI_CPPINCLUDE')])
        if not config.CheckCXXHeader('jni.h'):
            # not found; try to find
            if not config.CheckJNI():
                sys.stderr.write("Error: jni.h not found.\n"
                                 + "Please set JAVA_HOME environment variable "
                                 + "with $JAVA_HOME/bin/javac, $JAVA_HOME/include/jni.h\n"
                                 + "or directly $JNI_CPPINCLUDE with $JNI_CPPINCLUDE/jni.h\n")
                sys.exit(1)
    else:
        print 'Warning: Java support ("SG_JAVA") not enabled.'

    # now set up all further environment settings that should never fail
    # compiler setup should be always after checking headers and flags, as they can make the checks invalid
    # e.g. by setting "-Werror"

    # TODO check
    if env['PLATFORM'] not in ['cygwin', 'win32']:
        if env['OPT'] == True:
           env.Append(CPPFLAGS=['-O3', '-g'])
        else:
           env.Append(CPPFLAGS=['-g', '-O0'])

    if not env['USE_DOUBLE_PRECISION']:
       env.Append(CPPFLAGS=['-DUSE_DOUBLE_PRECISION=0'])

    # make settings case-insensitive
    env['COMPILER'] = env['COMPILER'].lower()
    env['ARCH'] = env['ARCH'].lower()

    if env['COMPILER'] == 'gnu':
        gcc_ver_str = subprocess.check_output([env['CXX'], '-dumpversion'])
        gcc_ver = env._get_major_minor_revision(gcc_ver_str)
        print "Using default gcc " + gcc_ver_str

        allWarnings = "-Wall -pedantic -pedantic-errors -Wextra \
            -Wcast-align -Wcast-qual -Wconversion -Wdisabled-optimization -Wformat=2 \
            -Wformat-nonliteral -Wformat-security -Wformat-y2k -Wimport  -Winit-self  \
            -Winvalid-pch -Wmissing-field-initializers -Wmissing-format-attribute -Wmissing-include-dirs \
             -Wpacked   -Wpointer-arith -Wredundant-decls -Wstack-protector \
            -Wstrict-aliasing=2 -Wswitch-default -Wswitch-enum -Wunreachable-code -Wunused -Wunused-parameter \
            -Wvariadic-macros -Wwrite-strings -Wuninitialized".split(" ")
        # rather uninteresting: -Wlong-long -Wpadded -Wshadow -Wfloat-equal -Waggregate-return -Wimplicit -Wmissing-noreturn -Weffc++
        # cannot really use:

        # -fno-strict-aliasing: http://www.swig.org/Doc1.3/Java.html or http://www.swig.org/Release/CHANGES, 03/02/2006
        #    "If you are going to use optimisations turned on with gcc > 4.0 (for example -O2),
        #     ensure you also compile with -fno-strict-aliasing"
        env.Append(CPPFLAGS=allWarnings + [
                             '-Wno-unused-parameter',
                             '-fno-strict-aliasing',
                             '-funroll-loops', '-mfpmath=sse',
                             '-DDEFAULT_RES_THRESHOLD=-1.0', '-DTASKS_PARALLEL_UPDOWN=4'])
        env.Append(CPPFLAGS=['-fopenmp'])
        env.Append(LINKFLAGS=['-fopenmp'])

        # required for profiling
        env.Append(CPPFLAGS=['-fno-omit-frame-pointer'])

        if env['USE_STATICLIB']:
            env.Append(CPPFLAGS=['-D_USE_STATICLIB'])

        if not env['USE_DOUBLE_PRECISION']:
            if gcc_ver >= (4, 9, 0):
                # disable warnings which occur for, e.g., "SGPP::float_t value = 1.0/3.0;"
                # (-Wno-float-conversion was introduced with g++ 4.9)
                env.Append(CPPFLAGS=['-Wno-float-conversion'])
            else:
                # disable all conversion warnings
                env.Append(CPPFLAGS=['-Wno-conversion'])

        if env['ARCH'] == 'sse3':
            config.env.AppendUnique(CPPFLAGS=["-msse3"])
        elif env['ARCH'] == 'sse42':
            config.env.AppendUnique(CPPFLAGS=["-msse4.2"])
        elif env['ARCH'] == 'avx':
            config.env.AppendUnique(CPPFLAGS=["-mavx"])
        elif env['ARCH'] == 'fma4':
            config.env.AppendUnique(CPPFLAGS=["-mavx"])
            config.env.AppendUnique(CPPFLAGS=["-mfma4"])
        elif env['ARCH'] == 'avx2':
            config.env.AppendUnique(CPPFLAGS=["-mavx2"])
            config.env.AppendUnique(CPPFLAGS=["-mfma"])
        elif env['ARCH'] == 'avx512':
            config.env.AppendUnique(CPPFLAGS=["-mavx512f"])
            config.env.AppendUnique(CPPFLAGS=["-mavx512cd"])
            config.env.AppendUnique(CPPFLAGS=["-mfma"])
        else:
            print "You must specify a valid ARCH value for gnu."
            print "Available configurations are: sse3, sse42, avx, fma4, avx2, avx512"
            sys.exit(1)

        # check if using MinGW (g++ on win32)
        if env['PLATFORM'] == 'win32':
            # disable warnings which occur when including Boost in the tests
            env.Append(CPPFLAGS=['-Wno-switch-enum',
                                 '-Wno-deprecated-declarations'])
            # also use "lib" prefix on MinGW for consistency with Linux
            # (default is no prefix)
            env['SHLIBPREFIX'] = 'lib'
    elif env['COMPILER'] == 'clang':
        print "Using clang"

        env['CC'] = ('clang')
        env['LINK'] = ('clang++')
        env['CXX'] = ('clang++')

        allWarnings = "-Wall -Wextra".split(" ")

        # -fno-strict-aliasing: http://www.swig.org/Doc1.3/Java.html or http://www.swig.org/Release/CHANGES, 03/02/2006
        #    "If you are going to use optimisations turned on with gcc > 4.0 (for example -O2),
        #     ensure you also compile with -fno-strict-aliasing"
        env.Append(CPPFLAGS=allWarnings + [
                             '-DDEFAULT_RES_THRESHOLD=-1.0', '-DTASKS_PARALLEL_UPDOWN=4'])
        env.Append(CPPFLAGS=['-fopenmp=libomp'])
        env.Append(LINKFLAGS=['-fopenmp=libomp'])

        if env['USE_STATICLIB']:
            env.Append(CPPFLAGS=['-D_USE_STATICLIB'])

        if not env['USE_DOUBLE_PRECISION']:
            if gcc_ver >= (4, 9, 0):
                # disable warnings which occur for, e.g., "SGPP::float_t value = 1.0/3.0;"
                # (-Wno-float-conversion was introduced with g++ 4.9)
                env.Append(CPPFLAGS=['-Wno-float-conversion'])
            else:
                # disable all conversion warnings
                env.Append(CPPFLAGS=['-Wno-conversion'])

        if env['ARCH'] == 'sse3':
            config.env.AppendUnique(CPPFLAGS=["-msse3"])
        elif env['ARCH'] == 'sse42':
            config.env.AppendUnique(CPPFLAGS=["-msse4.2"])
        elif env['ARCH'] == 'avx':
            config.env.AppendUnique(CPPFLAGS=["-mavx"])
        elif env['ARCH'] == 'fma4':
            config.env.AppendUnique(CPPFLAGS=["-mavx"])
            config.env.AppendUnique(CPPFLAGS=["-mfma4"])
        elif env['ARCH'] == 'avx2':
            config.env.AppendUnique(CPPFLAGS=["-mavx2"])
            config.env.AppendUnique(CPPFLAGS=["-mfma"])
        elif env['ARCH'] == 'avx512':
            config.env.AppendUnique(CPPFLAGS=["-mavx512f"])
            config.env.AppendUnique(CPPFLAGS=["-mavx512cd"])
            config.env.AppendUnique(CPPFLAGS=["-mfma"])
        else:
            print "You must specify a valid ARCH value for gnu."
            print "Available configurations are: sse3, sse4.2, avx, fma4, avx2, avx512"
            sys.exit(1)

    elif env['COMPILER'] == 'intel':
        print "Using icc"
        env.AppendUnique(CPPFLAGS=['-Wall', '-ansi', '-Wno-deprecated', '-wd1125',
                               '-fno-strict-aliasing',
                               '-ip', '-ipo', '-funroll-loops',
                               '-ansi-alias', '-fp-speculation=safe',
                               '-DDEFAULT_RES_THRESHOLD=-1.0', '-DTASKS_PARALLEL_UPDOWN=4', '-no-offload'])

        env['CC'] = ('icc')
        env['LINK'] = ('icpc')
        env['CXX'] = ('icpc')

        env.AppendUnique(CPPFLAGS=['-openmp'])
        env.AppendUnique(LINKFLAGS=['-openmp'])

        if env['USE_STATICLIB']:
            env.AppendUnique(CPPFLAGS=['-D_USE_STATICLIB'])

        if not env['USE_DOUBLE_PRECISION']:
            if gcc_ver >= (4, 9, 0):
                # disable warnings which occur for, e.g., "SGPP::float_t value = 1.0/3.0;"
                # (-Wno-float-conversion was introduced with g++ 4.9)
                env.AppendUnique(CPPFLAGS=['-Wno-float-conversion'])
            else:
                # disable all conversion warnings
                env.AppendUnique(CPPFLAGS=['-Wno-conversion'])

        if env['ARCH'] == 'sse3':
            config.env.AppendUnique(CPPFLAGS=["-msse3"])
        elif env['ARCH'] == 'sse42':
            config.env.AppendUnique(CPPFLAGS=["-msse4.2"])
        elif env['ARCH'] == 'avx':
            config.env.AppendUnique(CPPFLAGS=["-mavx"])
        elif env['ARCH'] == 'avx2':
            config.env.AppendUnique(CPPFLAGS=["-xCORE-AVX2"])
            config.env.AppendUnique(CPPFLAGS=["-fma"])
        elif env['ARCH'] == 'avx512':
            config.env.AppendUnique(CPPFLAGS=["-xCOMMON-AVX512"])
            config.env.AppendUnique(CPPFLAGS=["-fma"])
        elif env['ARCH'] == 'mic':
            config.env.AppendUnique(CPPFLAGS=["-mmic"])
            config.env.AppendUnique(LINKFLAGS=['-mmic'])
        else:
            print "You must specify a valid ARCH value for intel."
            print "Available configurations are: sse3, sse4.2, avx, avx2, avx512, mic"
            sys.exit(1)

        env.AppendUnique(CPPPATH=[distutils.sysconfig.get_python_inc()])
    else:
        print "You must specify a valid value for Compiler."
        print "Available configurations are: gnu, clang, and intel"
        sys.exit(1)

    # special treatment for different platforms
    if env['PLATFORM'] == 'darwin':
        # the "-undefined dynamic_lookup"-switch is required to actually build a shared library
        # in OSX. "-dynamiclib" alone results in static linking of all further dependent shared libraries
        # beware: if symbols are missing that are actually required (because the symbols don't reside in a shared library), there will be no error during compilation
        # the python binding (pysgpp) requires lpython and a flat namespace
        # also for the python binding, the library must be suffixed with '*.so' even though it is a dynamiclib and not a bundle (see SConscript in src/pysgpp)
        env.AppendUnique(LINKFLAGS=['-flat_namespace', '-undefined', 'dynamic_lookup', '-lpython'])
        # The GNU assembler (GAS) is not supported in Mac OS X. A solution that fixed this problem is by adding -Wa,-q to the compiler flags.
        # From the man pages for as (version 1.38): -q Use the clang(1) integrated assembler instead of the GNU based system assembler.
        # Note that the CPPFLAG is exactly "-Wa,-q", where -Wa passes flags to the assembler and -q is the relevant flag to make it use integrated assembler
        env.AppendUnique(CPPFLAGS=['-Wa,-q'])
        env.AppendUnique(CPPPATH="/usr/local/include")
        env.AppendUnique(LIBPATH="/usr/local/lib")
        env['SHLIBSUFFIX'] = '.dylib'
    elif env['PLATFORM'] == 'cygwin':
        # required to find the static libraries compiled before the shared libraries
        # the static libraries are required as the linker on windows cannot ignore undefined symbols
        # (as is done on linux automatically and is done on OSX with the settings above)
        #env.Append(LIBPATH=[BUILD_DIR])
        pass

    # will lead to a warning on cygwin and win32
    # ("all code is position independent")
    if env['PLATFORM'] not in ['cygwin', 'win32']:
        env.AppendUnique(CPPFLAGS=['-fPIC'])

    # setup the include base folder
    # env.Append(CPPPATH=['#/src/sgpp'])
    for moduleFolder in moduleFolders:
      if (moduleFolder in languageWrapperFolders) or \
          (not env['SG_' + moduleFolder.upper()]):
        continue
      env.AppendUnique(CPPPATH=['#/' + moduleFolder + '/src/'])

    # check for mpic++
    if not env['CXX']=='mpic++':
        env['SG_PARALLEL'] = 0
        print 'Hint: not using mpic++, parallel module ("SG_PARALLEL") disabled, since it requires mpic++'
    elif env['SG_PARALLEL'] != 0:
        env['CPPDEFINES']['USE_MPI'] = '1'
        print 'Parallel module ("SG_PARALLEL") enabled'
    else:
        print 'Parallel module ("SG_PARALLEL") disabled'

    # detour compiler output
    env['PRINT_CMD_LINE_FUNC'] = Helper.print_cmd_line

    env = config.Finish()

    # clear build_log file
    with open(env['CMD_LOGFILE'], 'a') as logFile:
        logFile.seek(0)
        logFile.truncate()
Ejemplo n.º 12
0
    def __init__(
        self,
        _platform=None,
        _tools=None,
        toolpath=None,
        variables=None,
        parse_flags=None,
        **kw
    ):
        """Create a new BaseEnvironment instance."""

        if _tools is None:
            toolset = kw.setdefault('ARGUMENTS', {}).get('toolset', os.environ.get('FREELAN_TOOLSET', 'default'))
            _tools = [toolset, 'astyle', 'doxygen', 'nsis', 'innosetup']

        if toolpath is None:
            toolpath = [os.path.abspath(os.path.dirname(__file__))]

        self.arch = kw.setdefault('ARGUMENTS', {}).get('arch', os.environ.get('FREELAN_ARCH', platform.machine()))

        kw.setdefault('TARGET_ARCH', self.arch)

        SConsEnvironment.__init__(
            self,
            _platform,
            _tools,
            toolpath,
            variables,
            parse_flags,
            **kw
        )

        self.mode = kw.setdefault('ARGUMENTS', {}).get('mode', os.environ.get('FREELAN_MODE', 'release'))
        self.bindir = kw.setdefault('ARGUMENTS', {}).get('bindir', os.environ.get('FREELAN_BINDIR', 'bin'))
        self.libdir = kw.setdefault('ARGUMENTS', {}).get('libdir', os.environ.get('FREELAN_LIBDIR', 'lib'))
        self.static_suffix = kw.setdefault('ARGUMENTS', {}).get('static_suffix', os.environ.get('FREELAN_STATIC_SUFFIX', '_static'))

        if not self.mode in ['release', 'debug']:
            raise ValueError('\"mode\" can be either \"release\" or \"debug\"')

        # Parse environment overloads
        if 'ENV' in kw:
            for key, value in kw['ENV'].items():
                if key.startswith('FREELAN_ENV_'):
                    self[key[len('FREELAN_ENV_'):]] = value

        if not 'CXXFLAGS' in self:
            self['CXXFLAGS'] = []
            # begin openwrt, ugly hardcoded patch due to the fact exported linux env variableS  cannot be converted into python arrays
            # => FREELAN_ENV_CXXFLAGS="-I/home/log/openwrt/trunk/staging_dir/target-mips_r2_uClibc-0.9.33.2/usr/include -I/home/log/openwrt/freelan/freelan-all/libcryptoplus/include ..."
            self['CXXFLAGS'] = ["-I/home/log/openwrt/trunk/staging_dir/target-mips_r2_eglibc-2.13/usr/include","-I/home/log/openwrt/freelan/freelan-all/libcryptoplus/include","-I/home/log/openwrt/trunk/build_dir/target-mips_r2_eglibc-2.13/libiconv/include","-I/home/log/openwrt/freelan/freelan-all/libfscp/include","-I/home/log/openwrt/freelan/freelan-all/libasiotap/include","-I/home/log/openwrt/freelan/freelan-all/libfreelan/include"]
            # end openwrt

        if not 'LINKFLAGS' in self:
            self['LINKFLAGS'] = []
            
            # begin openwrt, same ugly patch for linked libs
            self['LINKFLAGS'] = ["-L/home/log/openwrt/trunk/staging_dir/target-mips_r2_eglibc-2.13/usr/lib","-L/home/log/openwrt/freelan/freelan-all/libcryptoplus/lib","-L/home/log/openwrt/trunk/build_dir/target-mips_r2_eglibc-2.13/libiconv","-L/home/log/openwrt/freelan/freelan-all/libfscp/lib","-L/home/log/openwrt/freelan/freelan-all/libasiotap/lib","-L/home/log/openwrt/freelan/freelan-all/libfreelan/lib"]
            # end openwrt            

        if not 'SHLINKFLAGS' in self:
            self['SHLINKFLAGS'] = []
Ejemplo n.º 13
0
    def __init__(self, path=None, os_platform=None, parse_flags=None, **kw):

        # Variables
        if path:
            variable_file = os.path.join(path, Environment._VARIABLE_FILE)
        else:
            variable_file = Environment._VARIABLE_FILE

        variables = Environment._create_variables(variable_file)

        # Tools
        if sys.platform == 'win32':
            toolset = 'mingw'
        else:
            toolset = 'default'

        tools = [toolset, 'doxygen', 'astyle']
        toolpath = [os.path.abspath(os.path.dirname(__file__))]

        # Parent constructor
        SConsEnvironment.__init__(self, os_platform, tools, toolpath,
                                  variables, parse_flags, **kw)

        self.variables_help_text = variables.GenerateHelpText(self)

        variables.Save(variable_file, self)

        self['arch'] = (self['arch'] in ['64', 'x86_64']) and '64' or '32'

        if not 'CXXFLAGS' in self:
            self['CXXFLAGS'] = []

        if not 'LIBPATH' in self:
            self['LIBPATH'] = []

        if not 'LIBS' in self:
            self['LIBS'] = []

        if not 'SHLINKFLAGS' in self:
            self['SHLINKFLAGS'] = []

        # Build with debug symbols or not
        if self['mode'] == 'debug':
            self['CXXFLAGS'].append('-g')
        else:
            self['CXXFLAGS'].append('-DNDEBUG')

        self['CXXFLAGS'] += [
            '-Wall', '-Wextra', '-Werror', '-pedantic', '-Wredundant-decls',
            '-O3', '-Wno-uninitialized', '-Wno-long-long', '-Wshadow'
        ]

        # Members
        if self['arch'] == '32':
            self.__libdir = 'lib'
        elif self['arch'] == '64':
            self.__libdir = 'lib64'

        if sys.platform != 'darwin':
            if self['arch'] == '32':
                self['CXXFLAGS'].append('-m32')
                self['LINKFLAGS'].append('-m32')
            elif self['arch'] == '64':
                self['CXXFLAGS'].append('-m64')
                self['LINKFLAGS'].append('-m64')
        else:
            self['CXXFLAGS'] += ['-arch', 'i386', '-arch', 'x86_64']

        if sys.platform == 'win32':
            self['CXXFLAGS'].append('-D_WIN32_WINNT=0x0501')

            self['CXXFLAGS'].append(
                '-isystem' +
                os.path.abspath(os.path.join(self['mingw_path'], 'include')))
            self['CXXFLAGS'].append('-isystem' + os.path.abspath(
                os.path.join(self['boost_path'], 'include', 'boost-' +
                             self['boost_version'])))
            self['CXXFLAGS'].append(
                '-isystem' +
                os.path.abspath(os.path.join(self['openssl_path'], 'include')))

            self['LIBPATH'].append(os.path.join(self['boost_path'], 'lib'))
            self['LIBPATH'].append(os.path.join(self['openssl_path'], 'lib'))
        else:
            if sys.platform.startswith('freebsd'):
                self['CXXFLAGS'].remove('-pedantic')
                self['CXXFLAGS'].append('-isystem' + os.path.abspath(
                    os.path.join(self['boost_path'], 'include')))

                self['LIBPATH'].append(os.path.join(self['boost_path'], 'lib'))
Ejemplo n.º 14
0
 def loadTools(self, tools):
     for tool in tools:
         SConsEnvironment.Tool(self, tool, MyTools.__path__)
Ejemplo n.º 15
0
    def __init__(
            self,
            path=None,
            os_platform=None,
            parse_flags=None,
            **kw):
        
        # Variables
        if path:
            variable_file = os.path.join(path, Environment._VARIABLE_FILE)
        else:
            variable_file = Environment._VARIABLE_FILE

        variables = Environment._create_variables(variable_file)

        # Tools
        if sys.platform == 'win32':
            toolset = 'mingw'
        else:
            toolset = 'default'

        tools = [toolset, 'doxygen', 'astyle']
        toolpath = [os.path.abspath(os.path.dirname(__file__))]

        # Parent constructor
        SConsEnvironment.__init__(self, os_platform, tools, toolpath, variables, parse_flags, **kw)

        self.variables_help_text = variables.GenerateHelpText(self)

        variables.Save(variable_file, self)

        self['arch'] = (self['arch'] in ['64', 'x86_64']) and '64' or '32'

        if not 'CXXFLAGS' in self:
            self['CXXFLAGS'] = []

        if not 'LIBPATH' in self:
            self['LIBPATH'] = []

        if not 'LIBS' in self:
            self['LIBS'] = []

        if not 'SHLINKFLAGS' in self:
            self['SHLINKFLAGS'] = []

        # Build with debug symbols or not
        if self['mode'] == 'debug':
            self['CXXFLAGS'].append('-g')
        else:
            self['CXXFLAGS'].append('-DNDEBUG')

        self['CXXFLAGS'] += ['-Wall', '-Wextra', '-Werror', '-pedantic', '-Wredundant-decls', '-O3', '-Wno-uninitialized', '-Wno-long-long', '-Wshadow']

        # Members
        if self['arch'] == '32':
            self.__libdir = 'lib'
        elif self['arch'] == '64':
            self.__libdir = 'lib64'

        if sys.platform != 'darwin':
            if self['arch'] == '32':
                self['CXXFLAGS'].append('-m32')
                self['LINKFLAGS'].append('-m32')
            elif self['arch'] == '64':
                self['CXXFLAGS'].append('-m64')
                self['LINKFLAGS'].append('-m64')
        else:
            self['CXXFLAGS'] += ['-arch', 'i386', '-arch', 'x86_64']

        if sys.platform == 'win32':
            self['CXXFLAGS'].append('-D_WIN32_WINNT=0x0501')
            
            self['CXXFLAGS'].append('-isystem' + os.path.abspath(os.path.join(self['mingw_path'], 'include')))
            self['CXXFLAGS'].append('-isystem' + os.path.abspath(os.path.join(self['boost_path'], 'include', 'boost-' + self['boost_version'])))
            self['CXXFLAGS'].append('-isystem' + os.path.abspath(os.path.join(self['openssl_path'], 'include')))

            self['LIBPATH'].append(os.path.join(self['boost_path'], 'lib'))
            self['LIBPATH'].append(os.path.join(self['openssl_path'], 'lib'))
        else:
            if sys.platform.startswith('freebsd'):
                self['CXXFLAGS'].remove('-pedantic')
                self['CXXFLAGS'].append('-isystem' + os.path.abspath(os.path.join(self['boost_path'], 'include')))

                self['LIBPATH'].append(os.path.join(self['boost_path'], 'lib'))
Ejemplo n.º 16
0
	def __init__(self, *args, **kwargs):
		additionalParams = {}
		additionalParams['CPPPATH'] = []
		additionalParams['CPPDEFINES'] = {}
		additionalParams['LIBPATH'] = []
		additionalParams['LIBS'] = []
		additionalParams['ENV'] = os.environ
		kwargs.update(additionalParams)
		SConsEnvironment.__init__(self, *args, **kwargs)

		#Stores SCons file signatures
		self.SConsignFile()

		#Caches implicit dependencies
		self.SetOption('implicit_cache', 1)

		#Do not fetch files from SCCS or RCS subdirectories
		#Desactivated: avoid extra searches and speed up the build a little
		self.SourceCode('.', None)

		#Sets the current compiler
		self.currentCC = None
		if self.CC.isMSVC(self):
			self.currentCC = self.CCMSVC()
			#FIXME This is done for compatibility reason
			self.GlobalAddDefines({'WIN32' : 1})
		elif self.CC.isGCC(self):
			self.currentCC = self.CCGCC()
		elif self.CC.isMinGW(self):
			self.currentCC = self.CCGCC()
		else:
			self.currentCC = self.CCGCC()

		#Build mode ('debug', 'release' or 'release-symbols')
		self.__buildMode = None

		#Parses the command line parameters
		self.__parseConsoleArguments()

		#Project name
		self.__projectName = None

		#Cannot do that here, this does not work
		#self.__saveCurrentBuildPath()
		#self.__saveCurrentSourcePath()

		#see WengoSetVariable() and WengoGetVariable()
		self.__variables = {}

		#Command line arguments
		self.__consoleArguments = {}
		for arg, value in ARGUMENTS.iteritems():
			self.__consoleArguments[arg] = value

		#Aliases, see Scons.Alias()
		#self.__aliases = {}

		#By default warnings are activated
		self.__activeWarnings()

		#System library (e.g Qt, boost...) or internal library?
		#By default internal library
		self.__isSystemLibrary = False

		#MacOS X app template path
		self.__macOSXTemplatePath = None
    def BlenderLib(self=None,
                   libname=None,
                   sources=None,
                   includes=[],
                   defines=[],
                   libtype='common',
                   priority=100,
                   compileflags=None,
                   cc_compileflags=None,
                   cxx_compileflags=None):
        global vcp
        if not self or not libname or not sources:
            print bc.FAIL + 'Cannot continue. Missing argument for BuildBlenderLib ' + libname + bc.ENDC
            self.Exit()

        def list_substring(quickie, libname):
            for q in quickie:
                if libname.find(q) != -1:
                    return True
            return False

        if list_substring(quickie, libname) or len(quickie) == 0:
            if list_substring(quickdebug, libname):
                print bc.HEADER + 'Configuring library ' + bc.ENDC + bc.OKGREEN + libname + bc.ENDC + bc.OKBLUE + " (debug mode)" + bc.ENDC
            else:
                print bc.HEADER + 'Configuring library ' + bc.ENDC + bc.OKGREEN + libname + bc.ENDC
            lenv = self.Clone()
            lenv.Append(CPPPATH=includes)
            lenv.Append(CPPDEFINES=defines)
            if lenv['BF_DEBUG'] or (libname in quickdebug):
                lenv.Append(CFLAGS=lenv['BF_DEBUG_CFLAGS'])
                lenv.Append(CCFLAGS=lenv['BF_DEBUG_CCFLAGS'])
                lenv.Append(CXXFLAGS=lenv['BF_DEBUG_CXXFLAGS'])
            else:
                lenv.Append(CFLAGS=lenv['REL_CFLAGS'])
                lenv.Append(CCFLAGS=lenv['REL_CCFLAGS'])
                lenv.Append(CXXFLAGS=lenv['REL_CXXFLAGS'])
            if lenv['BF_PROFILE']:
                lenv.Append(CFLAGS=lenv['BF_PROFILE_CFLAGS'])
                lenv.Append(CCFLAGS=lenv['BF_PROFILE_CCFLAGS'])
                lenv.Append(CXXFLAGS=lenv['BF_PROFILE_CXXFLAGS'])
            if compileflags:
                lenv.Replace(CFLAGS=compileflags)
            if cc_compileflags:
                lenv.Replace(CCFLAGS=cc_compileflags)
            if cxx_compileflags:
                lenv.Replace(CXXFLAGS=cxx_compileflags)
            lenv.Append(CFLAGS=lenv['C_WARN'])
            lenv.Append(CCFLAGS=lenv['CC_WARN'])
            lenv.Append(CXXFLAGS=lenv['CXX_WARN'])

            if lenv['OURPLATFORM'] == 'win64-vc':
                lenv.Append(LINKFLAGS=['/MACHINE:X64'])

            if lenv['OURPLATFORM'] in ('win32-vc', 'win64-vc'):
                if lenv['BF_DEBUG']:
                    lenv.Append(CCFLAGS=['/MTd'])
                else:
                    lenv.Append(CCFLAGS=['/MT'])

            targetdir = root_build_dir + 'lib/' + libname
            if not (root_build_dir[0] == os.sep or root_build_dir[1] == ':'):
                targetdir = '#' + targetdir
            lib = lenv.Library(target=targetdir, source=sources)
            SConsEnvironment.Default(
                self, lib
            )  # we add to default target, because this way we get some kind of progress info during build
            if self['BF_MSVS'] and self['OURPLATFORM'] in ('win32-vc',
                                                           'win64-vc'):
                #if targetdir[0] == '#':
                #    targetdir = targetdir[1:-1]
                print "! ", targetdir + '.vcproj'  # + self['MSVSPROJECTSUFFIX']
                vcproject = self.MSVSProject(
                    target=targetdir +
                    '.vcproj',  # + self['MSVSPROJECTSUFFIX'],
                    srcs=sources,
                    buildtarget=lib,
                    variant='Release',
                    auto_build_solution=0)
                vcp.append(vcproject)
                SConsEnvironment.Default(self, vcproject)
        else:
            print bc.WARNING + 'Not building ' + bc.ENDC + bc.OKGREEN + libname + bc.ENDC + ' for ' + bc.OKBLUE + 'BF_QUICK' + bc.ENDC
        # note: libs is a global
        add_lib_to_dict(self, libs, libtype, libname, priority)