Creating a python extension module with distutils

I use distutils to create a Python extension module written in C ++. The problem is that in order to compile the extension module I need to link to a specific shared library. For this, you need to set an additional compiler flag. So, I looked at the Python docs and found out about the extra_compile_args property of the Extension object. So I tried the following:

 from distutils.core import setup, Extension module = Extension('test', sources = ['test.cpp']) module.extra_compile_args = ['--std=c++0x', '-l mylib']; setup(name = 'test', version = '1.0', ext_modules = [module]) 

This is like compiling, except when I import my module into Python, it throws an ImportError exception due to the undefined character. Thus, apparently, the library was not linked properly. So I tried to write a catchy C ++ program that was linked to a shared library, and everything worked out fine. Then I realized that something really strange was happening with distutils , because if I add a compilation argument that refers to the name of the dummy version library, distutils just compiles everything without a problem:

 module.extra_compile_args = ['--std=c++0x', '-l some_fake_library']; 

When I run setup.py build , the assembly works without errors!

So what is going on here? How can I compile an extension module that requires binding to a shared library?

+4
source share
2 answers

In fact, there is a special option for this.

For instance:

 libraries=["rt"] 

You leave the option and details lib.

+5
source

One of the goals of distutils is to make your code independent of one compiler. Your "-l somelib" looks like it works with GCC (although it should be "-lomelib", without a space). This is why you use the libraries option for the Extension class. Distutils will then pass the appropriate communication command to any compiler used.

You can also see the actual build commands that distutils uses and run them yourself to see what is going wrong.

+3
source

All Articles