Exemple #1
0
def textfeat_Extension(magick=False):
    import pkgconfig
    libs = ['opencv', 'libxml-2.0', 'Magick++']
    compile_args = ['-std=c++11']
    link_args = []
    for lib in libs:
        if not pkgconfig.exists(lib):
            raise FileNotFoundError('pkgconfig did not find ' + lib)
        compile_args += pkgconfig.cflags(lib).split()
        link_args += pkgconfig.libs(lib).split()
    #compile_args += pkgconfig.cflags('opencv').split()
    #cvre = re.compile('^-L|^-lopencv_core|^-lopencv_imgproc|^-lopencv_imgcodecs|^-lopencv_flann')
    #link_args += [x for x in pkgconfig.libs('opencv').split() if cvre.match(x)]
    cvinc = pkgconfig.cflags('opencv').split()[0].rsplit('/opencv', 1)[0]
    defimage = '__PAGEXML_IMG_MAGICK__' if magick else '__PAGEXML_IMG_CV__'
    pageimage = 'Magick::Image' if magick else 'cv::Mat'
    define_macros = [(defimage, ''), ('__PAGEXML_MAGICK__', '')]
    swig_opts = [
        '-D' + defimage, '-DPageImage=' + pageimage, '-D__PAGEXML_MAGICK__'
    ]
    print('textfeat_Extension configured with ' + defimage)
    return Extension(
        '_textfeat',
        define_macros=define_macros + [('SWIG_PYTHON_SILENT_MEMLEAK', '')],
        extra_compile_args=compile_args,
        extra_link_args=link_args,
        swig_opts=swig_opts + [cvinc, '-modern', '-keyword', '-c++'],
        sources=[
            'textfeat/TextFeatExtractor.i', 'textfeat/TextFeatExtractor.cc',
            'textfeat/intimg.cc', 'textfeat/mem.cc'
        ])
Exemple #2
0
def pagexml_Extension(magick):
    import pkgconfig
    libs = ['opencv', 'libxml-2.0', 'libxslt', 'gdal']
    if magick:
        libs += ['Magick++']
    compile_args = ['-std=c++11']
    link_args = []
    for lib in libs:
        if not pkgconfig.exists(lib):
            raise FileNotFoundError('pkgconfig did not find ' + lib)
        compile_args += pkgconfig.cflags(lib).split()
        link_args += pkgconfig.libs(lib).split()
    #compile_args += pkgconfig.cflags('opencv').split()
    #cvre = re.compile('^-L|^-lopencv_core|^-lopencv_imgproc|^-lopencv_imgcodecs|^-lopencv_highgui')
    #link_args += [x for x in pkgconfig.libs('opencv').split() if cvre.match(x)]
    cvinc = pkgconfig.cflags('opencv').split()[0].rsplit('/opencv', 1)[0]
    defimage = '__PAGEXML_IMG_MAGICK__' if magick else '__PAGEXML_IMG_CV__'
    pageimage = 'Magick::Image' if magick else 'cv::Mat'
    define_macros = [('__PAGEXML_OGR__', ''), (defimage, '')
                     ] + ([('__PAGEXML_MAGICK__', '')] if magick else [])
    swig_opts = [
        '-D__PAGEXML_OGR__', '-D' + defimage, '-DPageImage=' + pageimage
    ] + (['-D__PAGEXML_MAGICK__'] if magick else [])
    print('pagexml_Extension configured with ' + defimage)
    return Extension(
        '_pagexml',
        define_macros=define_macros + [('SWIG_PYTHON_SILENT_MEMLEAK', '')],
        extra_compile_args=compile_args,
        extra_link_args=link_args,
        swig_opts=swig_opts +
        [cvinc, '-I./opencv-swig/lib', '-modern', '-keyword', '-w511', '-c++'],
        sources=['pagexml/PageXML.i', 'pagexml/PageXML.cc'])
Exemple #3
0
def test_cflags():
    flags = pkgconfig.cflags(PACKAGE_NAME)

    for flag in flags.split(' '):
        assert flag in ('-DGSEAL_ENABLE', '-I/usr/include/gtk-3.0')

    with pytest.raises(pkgconfig.PackageNotFoundError):
        pkgconfig.cflags('doesnotexist')
Exemple #4
0
def test_cflags():
    flags = pkgconfig.cflags(PACKAGE_NAME)

    for flag in flags.split(' '):
        assert flag in ('-DGSEAL_ENABLE', '-I/usr/include/gtk-3.0')

    with pytest.raises(pkgconfig.PackageNotFoundError):
        pkgconfig.cflags('doesnotexist')
Exemple #5
0
def get_cflags(package):
    includes = pkgconfig.cflags(package)
    if not includes:
        raise RuntimeError('Unable to find pkgconfig cflags'
                           ' for {}'.format(package))
    includes = includes.replace('-I', '').split(' ')
    return includes
Exemple #6
0
def get_blas_config() -> PackageInfo:
    """
    Find CBLAS-compatible BLAS

    :return:
        blas related package information
    """

    blaspkgcfg = {
        'include_dirs': [],
        'library_dirs': [],
        'libraries': [],
        'define_macros': [],
        'extra_compile_args': [],
        'extra_link_args': []
    }

    # Check environment variables
    if 'BLAS_CFLAGS' in os.environ:
        blaspkgcfg['extra_compile_args'].extend(
            shlex.split(os.environ['BLAS_CFLAGS']))

    if 'BLAS_LIBS' in os.environ:
        blaspkgcfg['extra_link_args'].extend(
            shlex.split(os.environ['BLAS_LIBS']))

    if 'BLAS_CFLAGS' in os.environ or 'BLAS_LIBS' in os.environ:
        # If options have been provided by the user, we don't try to detect
        # anything by ourselves
        return blaspkgcfg

    # Try environment modules
    # MKL
    if 'MKLROOT' in os.environ:
        if 'MKL_INC' in os.environ:
            blaspkgcfg['extra_compile_args'].extend(
                shlex.split(os.environ['MKL_INC']))
        if 'MKL_LIB' in os.environ:
            blaspkgcfg['extra_link_args'].extend(
                shlex.split(os.environ['MKL_LIB']))
        blaspkgcfg['define_macros'].append(('AMICI_BLAS_MKL', None), )
        return blaspkgcfg

    # Try pkgconfig
    if pkgconfig:
        for blas_name in ['cblas', 'openblas']:
            if pkgconfig.exists(blas_name):
                blaspkgcfg = pkgconfig.parse(blas_name)
                blaspkgcfg['extra_compile_args'] = [
                    pkgconfig.cflags(blas_name)
                ]
                blaspkgcfg['extra_link_args'] = [pkgconfig.libs(blas_name)]

                return blaspkgcfg

    # If none of the previous worked, fall back to libcblas in default paths
    blaspkgcfg['libraries'] = ['cblas']

    return blaspkgcfg
Exemple #7
0
def pkg_include_dirs(pkg_name):
    includes = []
    for dir in pkgconfig.cflags(pkg_name).split(" "):
        if dir[:2] == "-I":
            includes.append(dir[2:])
        else:
            includes.append(dir)
    return includes
Exemple #8
0
def cython_aliases():
    """
    Return the aliases for compiling Cython code. These aliases are
    macros which can occur in ``# distutils`` headers.

    EXAMPLES::

        sage: from sage.env import cython_aliases
        sage: cython_aliases()
        {...}
        sage: sorted(cython_aliases().keys())
        ['ARB_LIBRARY',
         'FFLASFFPACK_CFLAGS',
         'FFLASFFPACK_INCDIR',
         'FFLASFFPACK_LIBDIR',
         'FFLASFFPACK_LIBRARIES',
         'GIVARO_CFLAGS',
         'GIVARO_INCDIR',
         'GIVARO_LIBDIR',
         'GIVARO_LIBRARIES',
         'GSL_CFLAGS',
         'GSL_INCDIR',
         'GSL_LIBDIR',
         'GSL_LIBRARIES',
         'LINBOX_CFLAGS',
         'LINBOX_INCDIR',
         'LINBOX_LIBDIR',
         'LINBOX_LIBRARIES',
         'SINGULAR_CFLAGS',
         'SINGULAR_INCDIR',
         'SINGULAR_LIBDIR',
         'SINGULAR_LIBRARIES']
    """
    import pkgconfig

    aliases = {}

    for lib in ['fflas-ffpack', 'givaro', 'gsl', 'linbox', 'Singular']:
        var = lib.upper().replace("-", "") + "_"
        aliases[var + "CFLAGS"] = pkgconfig.cflags(lib).split()
        pc = pkgconfig.parse(lib)
        # INCDIR should be redundant because the -I options are also
        # passed in CFLAGS
        aliases[var + "INCDIR"] = pc['include_dirs']
        aliases[var + "LIBDIR"] = pc['library_dirs']
        aliases[var + "LIBRARIES"] = pc['libraries']

    # LinBox needs special care because it actually requires C++11 with
    # GNU extensions: -std=c++11 does not work, you need -std=gnu++11
    # (this is true at least with GCC 7.2.0).
    #
    # Further, note that LinBox does not add any C++11 flag in its .pc
    # file (possibly because of confusion between CFLAGS and CXXFLAGS?).
    # This is not a problem in practice since LinBox depends on
    # fflas-ffpack and fflas-ffpack does add such a C++11 flag.
    aliases["LINBOX_CFLAGS"].append("-std=gnu++11")
    aliases["ARB_LIBRARY"] = os.environ.get('SAGE_ARB_LIBRARY', 'arb')
    return aliases
 def __init__(self):
     found_paskages = self._find_in_tree(root=os.path.dirname(cv2.__file__))
     if found_paskages:
         PKG_CONFIG_PATH = found_paskages[0][1]
         self._pkg_config_name = found_paskages[0][0]
         os.environ['PKG_CONFIG_PATH'] = PKG_CONFIG_PATH
         self._pkg_config_path = PKG_CONFIG_PATH
         self._cflags = pkgconfig.cflags(self._pkg_config_name)
         self._libs = pkgconfig.libs(self._pkg_config_name)
Exemple #10
0
def cython_aliases():
    """
    Return the aliases for compiling Cython code. These aliases are
    macros which can occur in ``# distutils`` headers.

    EXAMPLES::

        sage: from sage.env import cython_aliases
        sage: cython_aliases()
        {...}
        sage: sorted(cython_aliases().keys())
        ['FFLASFFPACK_CFLAGS',
         'FFLASFFPACK_INCDIR',
         'FFLASFFPACK_LIBDIR',
         'FFLASFFPACK_LIBRARIES',
         'GIVARO_CFLAGS',
         'GIVARO_INCDIR',
         'GIVARO_LIBDIR',
         'GIVARO_LIBRARIES',
         'GSL_CFLAGS',
         'GSL_INCDIR',
         'GSL_LIBDIR',
         'GSL_LIBRARIES',
         'LINBOX_CFLAGS',
         'LINBOX_INCDIR',
         'LINBOX_LIBDIR',
         'LINBOX_LIBRARIES',
         'SINGULAR_CFLAGS',
         'SINGULAR_INCDIR',
         'SINGULAR_LIBDIR',
         'SINGULAR_LIBRARIES']
    """
    import pkgconfig

    aliases = {}

    for lib in ['fflas-ffpack', 'givaro', 'gsl', 'linbox', 'Singular']:
        var = lib.upper().replace("-", "") + "_"
        aliases[var + "CFLAGS"] = pkgconfig.cflags(lib).split()
        pc = pkgconfig.parse(lib)
        # INCDIR should be redundant because the -I options are also
        # passed in CFLAGS
        aliases[var + "INCDIR"] = pc['include_dirs']
        aliases[var + "LIBDIR"] = pc['library_dirs']
        aliases[var + "LIBRARIES"] = pc['libraries']

    # LinBox needs special care because it actually requires C++11 with
    # GNU extensions: -std=c++11 does not work, you need -std=gnu++11
    # (this is true at least with GCC 7.2.0).
    #
    # Further, note that LinBox does not add any C++11 flag in its .pc
    # file (possibly because of confusion between CFLAGS and CXXFLAGS?).
    # This is not a problem in practice since LinBox depends on
    # fflas-ffpack and fflas-ffpack does add such a C++11 flag.
    aliases["LINBOX_CFLAGS"].append("-std=gnu++11")

    return aliases
def flags_from_config(config, path_resolver):
    flags = []

    for package in config.get('pkg_config_packages') or []:
        flags.extend(pkgconfig.cflags(package).split(' '))

    extra_flags = config.get('extra_c_flags') or []
    for flag in extra_flags:
        flags.extend([f for f in flag.split()])

    return flags
Exemple #12
0
def flags_from_config(config):
    flags = []

    for package in config.get('pkg_config_packages') or []:
        flags.extend(pkgconfig.cflags(package).split(' '))

    extra_flags = config.get('extra_c_flags') or []
    for flag in extra_flags:
        flags.extend([f for f in flag.split()])

    return flags
Exemple #13
0
def get_include_paths(library_names):
    if not isinstance(library_names, list):
        library_names = [library_names]

    # find search paths for libraries and header via pkg-config
    header_dirs = set()

    # for manually installed packages, env var PKG_CONFIG_PATH might need to be changed
    for library_name in library_names:
        os.environ["PKG_CONFIG_ALLOW_SYSTEM_CFLAGS"] = "1"
        cflags = pkgconfig.cflags(library_name)
        header_dirs.update(re.findall(r"(?<=-I)\S+", cflags))

    return header_dirs
def get_motr_cflags():
    try:
        # Motr devel rpm takes precedence over M0_SRC_DIR
        if pkgconfig.exists('motr'):
            return pkgconfig.cflags('motr').split()
    except EnvironmentError:
        # fall back to M0_SRC_DIR handling if `pkg-config` is not available in
        # the system
        pass

    return [
        '-g', '-Werror', '-Wall', '-Wextra', '-Wno-attributes',
        '-Wno-unused-parameter'
    ]
Exemple #15
0
def get_include_dirs():
    import pkgconfig
    import numpy

    if not pkgconfig.exists('eigen3'):
        raise Exception(
            'Missing `eigen3` library. Please install it using the package manager of your operating system'
        )

    np_include_dir = numpy.get_include()

    # We have to throw away the `-I` part of the `pkgconfig` output
    # because it is not part of the include directory.
    eigen3_include_dir = pkgconfig.cflags('eigen3')[2:]

    return [np_include_dir, eigen3_include_dir]
Exemple #16
0
def get_host_cflags():
    """
    Get compilation cflags.

    Returns:
        str[]: List of compiler flags.
    """
    return [
        "-x",
        "c++",
        "-std=c++11",
        # Workaround for issue with libc++
        "-D_GLIBCXX_USE_CXX11_ABI=0",
        "-I" + os.path.join(vp.computecpp_prefix, "include"),
        "-I" + resource_filename(__name__, os.path.join("lib", "include")),
    ] + pkgconfig.cflags("opencv").split()
def flags_from_config(config, path_resolver):
    flags = []

    for package in config.get('pkg_config_packages') or []:
        flags.extend(pkgconfig.cflags(package).split(' '))

    extra_flags = config.get('extra_c_flags') or []

    for extra_flag in extra_flags:
        extra_flag = extra_flag.strip()
        if extra_flag.startswith('-I'):
            path = extra_flag.split('-I')[1]
            flags.append('-I%s' % path_resolver.resolve_config_path(path))
        else:
            flags.append(extra_flag)

    return flags
def getBlasConfig():
    """
    Find CBLAS-compatible BLAS

    Arguments:

    Returns:

    Raises:

    """

    blaspkgcfg = {'include_dirs': [],
                  'library_dirs': [],
                  'libraries': [],
                  'define_macros': [],
                  'extra_compile_args': [],
                  'extra_link_args': []
                  }

    if platform.system() in ['Linux', 'Darwin']:
        blaspkgcfg['libraries'] = ['cblas']

    if pkgconfig:
        if pkgconfig.exists('cblas'):
            blaspkgcfg = pkgconfig.parse('cblas')
            blaspkgcfg['extra_compile_args'] = [pkgconfig.cflags('cblas')]
            blaspkgcfg['extra_link_args'] = [pkgconfig.libs('cblas')]

    if 'BLAS_CFLAGS' in os.environ:
        blaspkgcfg['extra_compile_args'].extend(
            shlex.split(os.environ['BLAS_CFLAGS'])
        )

    if 'BLAS_LIBS' in os.environ:
        blaspkgcfg['extra_link_args'].extend(
            shlex.split(os.environ['BLAS_LIBS'])
        )

    return blaspkgcfg
Exemple #19
0
def check_gromacs_dirs():
    ''' Check for GROMACS directories and flags
    '''
    import pkgconfig

    # If gromacs not in pkgconfig, return from here
    if not pkgconfig.exists('libgromacs'):
        return

    out = dict()

    cppflags_t = pkgconfig.re.split('\s+', pkgconfig.cflags('libgromacs'))
    out['cppflags'] = []
    out['ldflags'] = []
    out['include'] = []
    out['lib_dirs'] = []
    out['libs'] = []

    # Extract include directory and CXXFLAGS
    for flags in cppflags_t:
        if '-I' in flags:
            out['include'].append(flags[2:])
        else:
            out['cppflags'].append(flags)

    # Extract lib directory and LDFLAGS
    ldflags_t = pkgconfig.re.split('\s+', pkgconfig.libs('libgromacs'))
    for flags in ldflags_t:
        if '-L' in flags:
            out['lib_dirs'].append(flags[2:])
        elif '-l' in flags:
            out['libs'].append(flags[2:])
        else:
            out['ldflags'].append(flags)

    if '-fopenmp' not in out['ldflags']:
        out['ldflags'].append('-fopenmp')

    return out
Exemple #20
0
 def __init__(self, mujoco_path):
     self.mujoco_path = mujoco_path
     python_version = str(sys.version_info.major) + str(
         sys.version_info.minor)
     self.version = '%s_%s_%s' % (get_version(), python_version,
                                  self.build_base())
     self.extension = Extension(
         'mujoco_py.cymj',
         sources=[join(self.CYMJ_DIR_PATH, "cymj.pyx")],
         include_dirs=[
             self.CYMJ_DIR_PATH,
             join(mujoco_path, 'include'),
             np.get_include(),
             pkgconfig.cflags('osmesa')[2:],
         ],
         libraries=['mujoco200'],
         library_dirs=[join(mujoco_path, 'bin')],
         extra_compile_args=[
             '-fopenmp',  # needed for OpenMP
             '-w',  # suppress numpy compilation warnings
         ],
         extra_link_args=['-fopenmp'],
         language='c')
Exemple #21
0
#sets up all the environment variables required by openvdb
import pkgconfig
print pkgconfig.exists('glib-2.0')
print pkgconfig.cflags('boost')
import os
import subprocess as sub

def callcmd(cmd):
	p = sub.Popen(cmd,stdout=sub.PIPE,stderr=sub.PIPE, shell=True)
	output, errors = p.communicate()
	#print errors
	return output

def locatePathToFile(filename, guesses=[]):
	#check hypothesises first
	for guess in guesses:
		dirname=os.path.dirname(guess)
		if os.path.isdir(dirname):
			print "found "+filename+" in "+dirname
			return dirname
	#use the OS locate feature
	hypothesis=callcmd("locate "+filename)
	hlist=hypothesis.split("\n")
	dirname=os.path.dirname(hlist[0])
	if (not os.path.isdir(dirname)):
		raise Exception(filename+" not found!")
	print "found "+filename+" in "+dirname
	return dirname

def locateIncludeDir(dirname, file_inside, guesses=[]):
	"""
Exemple #22
0
typedef guint (*GHashFunc)(gconstpointer key);
typedef gboolean (*GEqualFunc)(gconstpointer a, gconstpointer b);

GHashTable* g_hash_table_new               (GHashFunc       hash_func,
                                            GEqualFunc      key_equal_func);

gboolean    g_hash_table_insert            (GHashTable     *hash_table,
                                            gpointer        key,
                                            gpointer        value);

void        g_hash_table_destroy           (GHashTable     *hash_table);

guint    g_str_hash     (gconstpointer  v);
gboolean g_str_equal    (gconstpointer  v1, gconstpointer  v1);
"""


ffi = FFI()
includes = pkgconfig.cflags('glib-2.0').replace('-I', '').split(' ')
# set source
ffi.set_source("_glib",
    """
    #include <glib.h>
    """,
    libraries=['glib-2.0'], include_dirs=includes)

ffi.cdef(cdef)

if __name__ == "__main__":
    ffi.compile(verbose=True)
Exemple #23
0
from setuptools import setup, Extension
from setuptools.command.install import install
import os
import ConfigParser

try:
    import pkgconfig
    cflags = pkgconfig.cflags('xmlsec1').replace('\\', '')
    if not cflags:
        raise
    libs = pkgconfig.libs('xmlsec1')
except Exception:
    import traceback
    print '-' * 100
    traceback.print_exc()
    print '-' * 100
    import platform
    cflags = ("-DXMLSEC_CRYPTO=\"openssl\" -D__XMLSEC_FUNCTION__=__FUNCTION__"
              " -DXMLSEC_NO_GOST=1 -DXMLSEC_NO_XKMS=1"
              " -DXMLSEC_NO_CRYPTO_DYNAMIC_LOADING=1 -DXMLSEC_OPENSSL_100=1"
              " -DXMLSEC_CRYPTO_OPENSSL=1"
              " -I/usr/include/libxml2 -I/usr/include/xmlsec1")

    if platform.uname()[4] == 'x86_64':
        cflags = "-DXMLSEC_NO_SIZE_T " + cflags
    libs = "-lxmlsec1-openssl -lxmlsec1 -lssl -lcrypto -lxslt -lxml2"

config = ConfigParser.ConfigParser()
config.read('setup.cfg')
locale_dir = config.get("compile_catalog", "directory")
domain = config.get("compile_catalog", "domain")
Exemple #24
0
    '-D_DEBUG=1',
    '-DJUCER_LINUX_MAKE_6D53C8B4=1',
    '-DJUCE_APP_VERSION=0.0.8.10',
    '-DJUCE_APP_VERSION_HEX=0x80a',
    '-lcrypto',
    '-ldl',
    '-lpthread',
    '-lrt',
    '-I./JuceLibraryCode',
    '-I/opt/JUCE/modules',
]

pkgConfigFlags = []

for pflag in pkgConfigFlags:
    flagList = pkgconfig.cflags(pflag).split(' ')
    for f in flagList:
        flags.append(f)

for dirname, subdirList, fileList in os.walk('./Source'):
    flags.append('-I' + dirname)


def DirectoryOfThisScript():
    return os.path.dirname(os.path.abspath(__file__))


def FlagsForFile(filename, **kwargs):
    return {
        'flags': flags,
        'include_paths_relative_to_dir': DirectoryOfThisScript()
Exemple #25
0
import sys

# Use the bundeled pkgconfig
here = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, here)
import pkgconfig

cfg_vars = distutils.sysconfig.get_config_vars()

for key, value in cfg_vars.items():
    if type(value) == str:
        cfg_vars[key] = value.replace("-Wstrict-prototypes", "")

extra_link_args = pkgconfig.libs('gsl').split()

extra_compile_args = pkgconfig.cflags('gsl').split()
extra_compile_args.append('-m64')

extension_mod = Extension(
    "_gappa",
    [
        "_gappa.cc", "../src/Radiation.C", "../src/Particles.C",
        "../src/Utils.C", "../src/Astro.C", "../src/2D_interp/interp2d.C",
        "../src/2D_interp/interp2d_spline.C", "../src/2D_interp/bilinear.C",
        "../src/2D_interp/bicubic.C"
    ],
    extra_compile_args=extra_compile_args,
    extra_link_args=extra_link_args,
    include_dirs=['../include'],
)
Exemple #26
0
    ])

if not py3c_found:
    include_dirs.append('py3c')

compiler = ccompiler.get_default_compiler()

extra_link_args = []
extra_compile_args = []

if compiler == 'msvc':
    extra_compile_args = ['/Ot', '/Wall']
elif compiler in ('unix', 'mingw32'):
    if liblz4_found and liblz4_pkgconfig:
        extra_link_args.append(pkgconfig.libs('liblz4'))
        if pkgconfig.cflags('liblz4'):
            extra_compile_args.append(pkgconfig.cflags('liblz4'))
    else:
        extra_compile_args = ['-O3', '-Wall', '-Wundef']
else:
    print('Unrecognized compiler: {0}'.format(compiler))
    sys.exit(1)

lz4version = Extension(
    'lz4._version',
    lz4version_sources,
    extra_compile_args=extra_compile_args,
    extra_link_args=extra_link_args,
    libraries=libraries,
    include_dirs=include_dirs,
    library_dirs=library_dirs,
Exemple #27
0
def test_cflags():
    flags = pkgconfig.cflags(PACKAGE_NAME)

    for flag in flags.split(' '):
        nt.assert_true(flag in ('-DGSEAL_ENABLE', '-I/usr/include/gtk-3.0'))
Exemple #28
0
def test_cflags():
    flags = pkgconfig.cflags(PACKAGE_NAME)

    for flag in flags.split(' '):
        nt.assert_true(flag in ('-DGSEAL_ENABLE', '-I/usr/include/gtk-3.0'))
Exemple #29
0
from setuptools import setup, Extension
from setuptools.command.install import install
import os
import ConfigParser

try:
    import pkgconfig
    cflags = pkgconfig.cflags('xmlsec1').replace('\\', '')
    if not cflags:
        raise
    libs = pkgconfig.libs('xmlsec1')
except Exception:
    import traceback
    print '-' * 100
    traceback.print_exc()
    print '-' * 100
    import platform
    cflags = ("-DXMLSEC_CRYPTO=\"openssl\" -D__XMLSEC_FUNCTION__=__FUNCTION__"
              " -DXMLSEC_NO_GOST=1 -DXMLSEC_NO_XKMS=1"
              " -DXMLSEC_NO_CRYPTO_DYNAMIC_LOADING=1 -DXMLSEC_OPENSSL_100=1"
              " -DXMLSEC_CRYPTO_OPENSSL=1"
              " -I/usr/include/libxml2 -I/usr/include/xmlsec1")

    if platform.uname()[4] == 'x86_64':
        cflags = "-DXMLSEC_NO_SIZE_T " + cflags
    libs = "-lxmlsec1-openssl -lxmlsec1 -lssl -lcrypto -lxslt -lxml2"

config = ConfigParser.ConfigParser()
config.read('setup.cfg')
locale_dir = config.get("compile_catalog", "directory")
domain = config.get("compile_catalog", "domain")
Exemple #30
0
from distutils.core import setup, Extension
import os
import sys

# Use the bundeled pkgconfig
here = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, here)
import pkgconfig

extra_link_args = pkgconfig.libs('gsl').split()

extra_compile_args = pkgconfig.cflags('gsl').split()
extra_compile_args.append('-std=c++11')

extension_mod = Extension(
    "_gappa",
    ["_gappa.cc", "../src/Radiation.C", "../src/Particles.C", "../src/Utils.C", "../src/Astro.C"],
    extra_compile_args=extra_compile_args,
    extra_link_args=extra_link_args,
    include_dirs=['../include'],
)

setup(
    name="gappa",
    ext_modules=[extension_mod],
)
Exemple #31
0
def cython_aliases():
    """
    Return the aliases for compiling Cython code. These aliases are
    macros which can occur in ``# distutils`` headers.

    EXAMPLES::

        sage: from sage.env import cython_aliases
        sage: cython_aliases()
        {...}
        sage: sorted(cython_aliases().keys())
        ['ARB_LIBRARY',
         'CBLAS_CFLAGS',
         ...,
         'ZLIB_LIBRARIES']
    """
    import pkgconfig

    aliases = {}

    for lib in ['fflas-ffpack', 'givaro', 'gsl', 'linbox', 'Singular',
                'libpng', 'gdlib', 'm4ri', 'zlib', 'cblas', 'lapack']:
        var = lib.upper().replace("-", "") + "_"
        if lib == 'cblas':
            lib = get_cblas_pc_module_name()
        if lib == 'zlib':
            aliases[var + "CFLAGS"] = ""
            try:
                pc = pkgconfig.parse('zlib')
                libs = pkgconfig.libs(lib)
            except pkgconfig.PackageNotFoundError:
                from collections import defaultdict
                pc = defaultdict(list, {'libraries': ['z']})
                libs = "-lz"
        else:
            aliases[var + "CFLAGS"] = pkgconfig.cflags(lib).split()
            pc = pkgconfig.parse(lib)
            libs = pkgconfig.libs(lib)
        # It may seem that INCDIR is redundant because the -I options are also
        # passed in CFLAGS.  However, "extra_compile_args" are put at the end
        # of the compiler command line.  "include_dirs" go to the front; the
        # include search order matters.
        aliases[var + "INCDIR"] = pc['include_dirs']
        aliases[var + "LIBDIR"] = pc['library_dirs']
        aliases[var + "LIBEXTRA"] = list(filter(lambda s: not s.startswith(('-l','-L')), libs.split()))
        aliases[var + "LIBRARIES"] = pc['libraries']

    # uname-specific flags
    UNAME = os.uname()

    def uname_specific(name, value, alternative):
        if name in UNAME[0]:
            return value
        else:
            return alternative

    aliases["LINUX_NOEXECSTACK"] = uname_specific("Linux", ["-Wl,-z,noexecstack"],
                                                  [])
    aliases["CYGWIN_SQLITE3_LIBS"] = uname_specific("CYGWIN", ["sqlite3"],
                                                    [])

    # LinBox needs special care because it actually requires C++11 with
    # GNU extensions: -std=c++11 does not work, you need -std=gnu++11
    # (this is true at least with GCC 7.2.0).
    #
    # Further, note that LinBox does not add any C++11 flag in its .pc
    # file (possibly because of confusion between CFLAGS and CXXFLAGS?).
    # This is not a problem in practice since LinBox depends on
    # fflas-ffpack and fflas-ffpack does add such a C++11 flag.
    aliases["LINBOX_CFLAGS"].append("-std=gnu++11")
    aliases["ARB_LIBRARY"] = ARB_LIBRARY

    # TODO: Remove Cygwin hack by installing a suitable cblas.pc
    if os.path.exists('/usr/lib/libblas.dll.a'):
        aliases["CBLAS_LIBS"] = ['gslcblas']

    try:
        aliases["M4RI_CFLAGS"].remove("-pedantic")
    except ValueError:
        pass

    # Determine ecl-specific compiler arguments using the ecl-config script
    ecl_cflags = subprocess.run([ECL_CONFIG, "--cflags"], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True).stdout.split()
    aliases["ECL_CFLAGS"] = list(filter(lambda s: not s.startswith('-I'), ecl_cflags))
    aliases["ECL_INCDIR"] = list(map(lambda s: s[2:], filter(lambda s: s.startswith('-I'), ecl_cflags)))
    ecl_libs = subprocess.run([ECL_CONFIG, "--libs"], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True).stdout.split()
    aliases["ECL_LIBDIR"] = list(map(lambda s: s[2:], filter(lambda s: s.startswith('-L'), ecl_libs)))
    aliases["ECL_LIBRARIES"] = list(map(lambda s: s[2:], filter(lambda s: s.startswith('-l'), ecl_libs)))
    aliases["ECL_LIBEXTRA"] = list(filter(lambda s: not s.startswith(('-l','-L')), ecl_libs))

    # NTL
    aliases["NTL_CFLAGS"] = ['-std=c++11']
    aliases["NTL_INCDIR"] = [NTL_INCDIR] if NTL_INCDIR else []
    aliases["NTL_LIBDIR"] = [NTL_LIBDIR] if NTL_LIBDIR else []
    aliases["NTL_LIBRARIES"] = ['ntl']
    aliases["NTL_LIBEXTRA"] = []

    return aliases
Exemple #32
0
GHashTable* g_hash_table_new               (GHashFunc       hash_func,
                                            GEqualFunc      key_equal_func);

gboolean    g_hash_table_insert            (GHashTable     *hash_table,
                                            gpointer        key,
                                            gpointer        value);

void        g_hash_table_destroy           (GHashTable     *hash_table);

guint    g_str_hash     (gconstpointer  v);
gboolean g_str_equal    (gconstpointer  v1, gconstpointer  v1);
"""

ffi = FFI()
includes = pkgconfig.cflags('glib-2.0')
if not includes:
    raise RuntimeError('Unable to find pkgconfig for glib-2.0')
includes = includes.replace('-I', '').split(' ')

# set source
ffi.set_source("_glib",
               """
    #include <glib.h>
    """,
               libraries=['glib-2.0'],
               include_dirs=includes)

ffi.cdef(cdef)

if __name__ == "__main__":
Exemple #33
0
from distutils.core import setup, Extension
import pkgconfig

GSL_CFLAGS = pkgconfig.cflags('gsl')
GSL_LIBS = pkgconfig.libs('gsl')

if(GSL_CFLAGS):
  COMPILEARGS=['-std=c++11', GSL_CFLAGS]
else:
  COMPILEARGS=['-std=c++11']

extension_mod = Extension("_gamerapy",
                          ["_gamerapy.cc", "../src/Radiation.C","../src/Particles.C","../src/Utils.C","../src/Astro.C"],
                          extra_compile_args=COMPILEARGS,
                          libraries=['gsl'],
                          include_dirs=['../include'],
)

setup(name = "gamerapy", ext_modules=[extension_mod])
Exemple #34
0
from codecs import open
import pkgconfig

here = path.abspath(path.dirname(__file__))

## Getting openbabel setting
openbabel = None
for ob in ['openbabel', 'openbabel-2.0']:
    if pkgconfig.exists(ob):
        openbabel = ob

if openbabel is None:
    raise LookupError("openbabel package not found")

pkgconfig.libs(openbabel)
openbabel_inc_dir = pkgconfig.cflags(openbabel)[2:]
openbabel_lib_dir = pkgconfig.re.split('\s+', pkgconfig.libs(openbabel))[0][2:]


class get_pybind_include(object):
    """Helper class to determine the pybind11 include path

    The purpose of this class is to postpone importing pybind11
    until it is actually installed, so that the ``get_include()``
    method can be invoked. """
    def __init__(self, user=False):
        self.user = user

    def __str__(self):
        import pybind11
        return pybind11.get_include(self.user)
Exemple #35
0
#!/usr/bin/env python3
#-*- encoding: utf-8 -*-

from distutils.core import setup, Extension
import pkgconfig

rdp_cflags = pkgconfig.cflags('rdp')
rdp_libs = pkgconfig.libs('rdp')

rdp_libs = rdp_libs.replace("-lrdp", "")
rdp_libs = rdp_libs.replace("-L", "")
rdp_libs = rdp_libs.strip()

rdp_libs = rdp_libs + "/librdp.a"

extra_compile_args = [rdp_cflags]
extra_link_args = ['-Wl,--whole-archive', rdp_libs, '-Wl,--no-whole-archive']

wrapper = Extension('rdp.wrapper', ['rdp/wrapper.c'],
                    extra_compile_args=extra_compile_args,
                    extra_link_args=extra_link_args)

packages = ['rdp']

print("PACKAGES = ", packages)

setup(name='rdp', version='1.0', packages=packages, ext_modules=[wrapper])
Exemple #36
0
if not "DARKNET_HOME" in os.environ:
    darknet_dir = input("$DARKNET_HOME:")
else:
    darknet_dir = os.environ["DARKNET_HOME"]

include_paths = [
    np.get_include(),
    os.path.join(darknet_dir, "include"),
    os.path.join(darknet_dir, "src")
]
libraries = ["darknet", "m", "pthread"]
library_paths = [darknet_dir]

extra_compiler_flags = [
    pkgconfig.cflags("opencv"),
    pkgconfig.cflags("python3")
]
extra_linker_flags = [pkgconfig.libs("opencv"), pkgconfig.libs("python3")]

ext_modules = [
    Extension("pydarknet", ["pydarknet.pyx", "pydarknet.pxd", "bridge.cpp"],
              include_dirs=include_paths,
              language="c++",
              libraries=libraries,
              library_dirs=library_paths,
              extra_link_args=extra_linker_flags,
              extra_compile_args=extra_compiler_flags),
]

setup(name='PyDarknet',
Exemple #37
0
    cmdclasses = {}
    setup_requires = []
    install_requires = []
    tests_require = []
else:
    from Cython.Build import cythonize
    from Cython.Distutils import build_ext
    import numpy
    import numpy.distutils

    try:
        import pkgconfig
        libs = ['blas', 'lapack', 'lapacke']
        extra_link_args = [pkgconfig.libs(lib) for lib in libs]
        include_dirs = (numpy.distutils.misc_util.get_numpy_include_dirs() +
                        [pkgconfig.cflags(lib) for lib in libs])
    except:
        extra_link_args = None
        include_dirs = None

    if extra_link_args is None or len(''.join(extra_link_args)) == 0:
        if sys.platform == 'darwin':
            print("Platform Detection: Mac OS X. Link to openblas...")
            extra_link_args = ['-L/usr/local/opt/openblas/lib -lopenblas']
            include_dirs = (
                numpy.distutils.misc_util.get_numpy_include_dirs() +
                ['/usr/local/opt/openblas/include'])
        else:
            # assume linux otherwise, unless we support Windows in the future...
            print("Platform Detection: Linux. Link to liblapacke...")
            extra_link_args = ['-L/usr/lib -llapacke -llapack -lblas']
Exemple #38
0
    for el in os.listdir():
        fname, ext = os.path.splitext(el)
        if ext == suffix:
            yield fname, el


if __name__ == '__main__':
    check_pkgconfig(['dbus-1'])
    p = argparse.ArgumentParser()
    p.add_argument('--clang', action='store_true', default=False)
    clang = p.parse_args().clang

    ninja_vars = OrderedDict(
        cxx=find_executable('clang++' if clang else 'c++'),
        cxxflags='-std=c++1z -Wall -Wextra -g -D_GNU_SOURCE',
        dbus_cflags=pkgconfig.cflags('dbus-1'),
        dbus_libs=pkgconfig.libs('dbus-1'),
        ninja=find_executable('ninja'))

    with open('build.ninja', 'w') as bf, open('.gitignore', 'w') as gign:
        bf.write('# Created by configure.py\n# DO NOT EDIT\n\n')
        n = ninja.ninja_syntax.Writer(bf)

        for key, val in ninja_vars.items():
            n.variable(key, val)
        n.newline()

        n.rule('link', '$cxx $cxxflags -o $out $in', 'CXXLD $out')
        n.rule('link-dbus',
               '$cxx $cxxflags $dbus_cflags -o $out $in $dbus_libs',
               'CXXLD $out')
Exemple #39
0
def cython_aliases(required_modules=None, optional_modules=None):
    """
    Return the aliases for compiling Cython code. These aliases are
    macros which can occur in ``# distutils`` headers.

    INPUT:

    - ``required_modules`` -- (default: taken from ``default_required_modules``)
      iterable of ``str`` values.

    - ``optional_modules`` -- (default: taken from ``default_optional_modules``)
      iterable of ``str`` values.

    EXAMPLES::

        sage: from sage.env import cython_aliases
        sage: cython_aliases()
        {...}
        sage: sorted(cython_aliases().keys())
        ['ARB_LIBRARY',
         'CBLAS_CFLAGS',
         ...,
         'ZLIB_LIBRARIES']
        sage: cython_aliases(required_modules=('module-that-is-assumed-to-not-exist'))
        Traceback (most recent call last):
        ...
        PackageNotFoundError: ...
        sage: cython_aliases(required_modules=(), optional_modules=('module-that-is-assumed-to-not-exist'))
        {...}

    TESTS:

    We can use ``cython.parallel`` regardless of whether OpenMP is supported.
    This will run in parallel, if OpenMP is supported::

        sage: cython('''
        ....: #distutils: extra_compile_args = OPENMP_CFLAGS
        ....: #distutils: extra_link_args = OPENMP_CFLAGS
        ....: from cython.parallel import prange
        ....:
        ....: cdef int i
        ....: cdef int n = 30
        ....: cdef int sum = 0
        ....:
        ....: for i in prange(n, num_threads=4, nogil=True):
        ....:     sum += i
        ....:
        ....: print(sum)
        ....: ''')
        435
    """
    import pkgconfig
    import itertools

    if required_modules is None:
        required_modules = default_required_modules

    if optional_modules is None:
        optional_modules = default_optional_modules

    aliases = {}

    for lib, required in itertools.chain(
        ((lib, True) for lib in required_modules),
        ((lib, False) for lib in optional_modules)):
        var = lib.upper().replace("-", "") + "_"
        if lib == 'cblas':
            lib = get_cblas_pc_module_name()
        if lib == 'zlib':
            aliases[var + "CFLAGS"] = ""
            try:
                pc = pkgconfig.parse('zlib')
                libs = pkgconfig.libs(lib)
            except pkgconfig.PackageNotFoundError:
                from collections import defaultdict
                pc = defaultdict(list, {'libraries': ['z']})
                libs = "-lz"
        else:
            try:
                aliases[var + "CFLAGS"] = pkgconfig.cflags(lib).split()
                pc = pkgconfig.parse(lib)
                libs = pkgconfig.libs(lib)
            except pkgconfig.PackageNotFoundError:
                if required:
                    raise
                else:
                    continue

        # It may seem that INCDIR is redundant because the -I options are also
        # passed in CFLAGS.  However, "extra_compile_args" are put at the end
        # of the compiler command line.  "include_dirs" go to the front; the
        # include search order matters.
        aliases[var + "INCDIR"] = pc['include_dirs']
        aliases[var + "LIBDIR"] = pc['library_dirs']
        aliases[var + "LIBEXTRA"] = list(
            filter(lambda s: not s.startswith(('-l', '-L')), libs.split()))
        aliases[var + "LIBRARIES"] = pc['libraries']

    # uname-specific flags
    UNAME = os.uname()

    def uname_specific(name, value, alternative):
        if name in UNAME[0]:
            return value
        else:
            return alternative

    aliases["LINUX_NOEXECSTACK"] = uname_specific("Linux",
                                                  ["-Wl,-z,noexecstack"], [])
    aliases["CYGWIN_SQLITE3_LIBS"] = uname_specific("CYGWIN", ["sqlite3"], [])

    # LinBox needs special care because it actually requires C++11 with
    # GNU extensions: -std=c++11 does not work, you need -std=gnu++11
    # (this is true at least with GCC 7.2.0).
    #
    # Further, note that LinBox does not add any C++11 flag in its .pc
    # file (possibly because of confusion between CFLAGS and CXXFLAGS?).
    # This is not a problem in practice since LinBox depends on
    # fflas-ffpack and fflas-ffpack does add such a C++11 flag.
    if "LINBOX_CFLAGS" in aliases:
        aliases["LINBOX_CFLAGS"].append("-std=gnu++11")

    aliases["ARB_LIBRARY"] = ARB_LIBRARY

    # TODO: Remove Cygwin hack by installing a suitable cblas.pc
    if os.path.exists('/usr/lib/libblas.dll.a'):
        aliases["CBLAS_LIBS"] = ['gslcblas']

    try:
        aliases["M4RI_CFLAGS"].remove("-pedantic")
    except (ValueError, KeyError):
        pass

    # Determine ecl-specific compiler arguments using the ecl-config script
    ecl_cflags = subprocess.run([ECL_CONFIG, "--cflags"],
                                check=True,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE,
                                universal_newlines=True).stdout.split()
    aliases["ECL_CFLAGS"] = list(
        filter(lambda s: not s.startswith('-I'), ecl_cflags))
    aliases["ECL_INCDIR"] = list(
        map(lambda s: s[2:], filter(lambda s: s.startswith('-I'), ecl_cflags)))
    ecl_libs = subprocess.run([ECL_CONFIG, "--libs"],
                              check=True,
                              stdout=subprocess.PIPE,
                              stderr=subprocess.PIPE,
                              universal_newlines=True).stdout.split()
    aliases["ECL_LIBDIR"] = list(
        map(lambda s: s[2:], filter(lambda s: s.startswith('-L'), ecl_libs)))
    aliases["ECL_LIBRARIES"] = list(
        map(lambda s: s[2:], filter(lambda s: s.startswith('-l'), ecl_libs)))
    aliases["ECL_LIBEXTRA"] = list(
        filter(lambda s: not s.startswith(('-l', '-L')), ecl_libs))

    # NTL
    aliases["NTL_CFLAGS"] = ['-std=c++11']
    aliases["NTL_INCDIR"] = [NTL_INCDIR] if NTL_INCDIR else []
    aliases["NTL_LIBDIR"] = [NTL_LIBDIR] if NTL_LIBDIR else []
    aliases["NTL_LIBRARIES"] = ['ntl']
    aliases["NTL_LIBEXTRA"] = []

    # OpenMP
    aliases["OPENMP_CFLAGS"] = OPENMP_CFLAGS.split()
    aliases["OPENMP_CXXFLAGS"] = OPENMP_CXXFLAGS.split()

    return aliases
Exemple #40
0
    from collections import defaultdict
    zlib_pc = defaultdict(list, {'libraries': ['z']})
zlib_libs = zlib_pc['libraries']
zlib_library_dirs = zlib_pc['library_dirs']
zlib_include_dirs = zlib_pc['include_dirs']

#########################################################
### M4RI flags
#########################################################

m4ri_pc = pkgconfig.parse('m4ri')
m4ri_libs = m4ri_pc['libraries']
m4ri_library_dirs = m4ri_pc['library_dirs']
m4ri_include_dirs = m4ri_pc['include_dirs']

m4ri_extra_compile_args = pkgconfig.cflags('m4ri').split()
try:
    m4ri_extra_compile_args.remove("-pedantic")
except ValueError:
    pass

# END copied from module_list.py (but #29706 removes the original).

# This list defines the *order* of linking libraries. A library should
# be put *before* any library it links to. Cython allows
# defining libraries using "# distutils: libraries = LIB". However, if
# there are multiple libraries, the order is undefined so we need to
# manually reorder the libraries according to this list. The order is
# important in particular for Cygwin. Any libraries which are not
# listed here will be added at the end of the list (without changing
# their relative order).