4

So I have set up a c++ class with say class.cpp, class.h. class.cpp uses some functions from gsl (it has #include <gsl/gsl_blas.h>) I have no problem linking this to another c++ file main.cpp and I can compile it with

g++ -o main main.o class.o  -I/home/gsl/include -lm -L/home/gsl/lib -lgsl -lgslcblas

Also, without including the gsl libary in class.cpp, I have managed to create a cython file that uses my class in class.cpp, and it works.

However, when I try to combine these two (ie using a c++ class in cython, where the c++ class uses gsl functions), I do not know what to do. I guess I have to include the

I/home/gsl/include -lm -L/home/gsl/lib -lgsl -lgslcblas

somewhere in the setup file, but I dont know where or how. My setup.py looks like

from distutils.core import setup
from Cython.Build import cythonize

import os

os.environ["CC"] = "g++"
os.environ["CXX"] = "g++"

setup(
    name = "cy",
    ext_modules = cythonize('cy.pyx'),
)

and I have

# distutils: language = c++
# distutils: sources = class.cpp

in the beginning of my .pyx file.

Thanks for any help!

Jonathan Lindgren
  • 1,192
  • 3
  • 14
  • 31

2 Answers2

1

I suggest you to use the extra_compile_args option in your extension. I already wrote some answer that luckily uses GSL dependency here.

Customize following your needs, but it should work this way.

Hope this can help...

Community
  • 1
  • 1
Gauthier Boaglio
  • 10,054
  • 5
  • 48
  • 85
1

You can specify the required external libraries using the libraries, include_dirs and library_dirs parameters of the Extension class. For example:

from distutils.extension import Extension
from distutils.core import setup
from Cython.Build import cythonize
import numpy

myext = Extension("myext",
                  sources=['myext.pyx', 'myext.cpp'],
                  include_dirs=[numpy.get_include(), '/path/to/gsl/include'],
                  library_dirs=['/path/to/gsl/lib'],
                  libraries=['m', 'gsl', 'gslcblas'],
                  language='c++',
                  extra_compile_args=["-std=c++11"],
                  extra_link_args=["-std=c++11"])
setup(name='myproject',
      ext_modules=cythonize([myext]))

Here, the C++ class is defined in myext.cpp and the cython interface in myext.pyx. See also: Cython Documentation

sfinkens
  • 1,210
  • 12
  • 15