Linking Python and C++ with Boost.python

Here is the “hello world” example from the Boost.python tutorial. I found that attempting to configure the Boost.jam build system is far more confusing than using GNU make to build the examples. The following presentation should be much easier to understand. All files to build this example can be found in the Shocksolution_Examples repo on GitHub.

Save the following as hello_ext.C

char const* greet()
{
   return "hello, world";
}
 
#include <boost/python.hpp>
 
BOOST_PYTHON_MODULE(hello_ext)
{
    using namespace boost::python;
    def("greet", greet);
}

Save the following as Makefile:

# location of the Python header files
 
PYTHON_VERSION = 2.7
PYTHON_INCLUDE = /usr/include/python$(PYTHON_VERSION)
 
# location of the Boost Python include files and library
 
BOOST_INC = /usr/include
BOOST_LIB = /usr/lib
 
# compile mesh classes
TARGET = hello_ext
 
$(TARGET).so: $(TARGET).o
	g++ -shared -Wl,--export-dynamic $(TARGET).o -L$(BOOST_LIB) -lboost_python-$(PYTHON_VERSION) -L/usr/lib/python$(PYTHON_VERSION)/config -lpython$(PYTHON_VERSION) -o $(TARGET).so
 
$(TARGET).o: $(TARGET).C
	g++ -I$(PYTHON_INCLUDE) -I$(BOOST_INC) -fPIC -c $(TARGET).C

Save the following as test_hello.py

import hello_ext
print hello_ext.greet()

That’s it.

7 thoughts on “Linking Python and C++ with Boost.python

  1. Pingback: Configuring Boost::Python and Hello Boost « Paranoid Android

  2. Yati Sagade

    You saved me from the horrible hellhole this BoostJam is. It almost feels like it was crafted not to be used by anyone but the core developers. Thanks :)

    Reply
  3. Ross

    Craig, I expect you will get lots of traffic with your solution. I’ve been trying to get your files to compile, but I’m having a few Makefile issues. After editing with Nano to confirm tabs rather than spaces and converting to unix lifefeeds, I’m getting an error: make: hello_ext.o: Command not found. Any idea why make is viewing $(TARGET).o as a command?

    Reply
  4. Craig Post author

    Ross, the formatting of the Makefile in this post was causing a lot of problems. I have refomatted the Makefile in the post and added all necessary files for the example to my repo on GitHub (link is near the top of the post).

    Also, the version of Boost on my workstation now has separate library files for each Python version, so I modified the Makefile accordingly. Let me know if there are any further problems.

    Reply
  5. Ross

    Craig, brilliant work. After a few mods to my own python and boost lib paths, and checking the whitespace/tabs formatting, your Makefile worked like a charm. With no disrespect to the bjam fellows, I worked on bjam until I was about to pass out and realized I could probably build using good-old-fashioned make (with a little help). That’s when a search took me to your site. Thanks for unblocking the road.

    Reply