Oct 7, 2011

Making qmake aware of python

Overview

#include "Python.h"

int main()
{
    Py_Initialize();
    PyRun_SimpleString("print \'Hello qmake!\'");
    Py_Finalize();
    return 0;
}
If we want to compile c++ program in which an python interpreter embeded, we need to know where's the python.
g++ main.cpp -ID:\Python27\include D:\Python27\libs\python27.lib
So how can we avoid using the specific path such as D:\Python27?

Cmake

If we using cmake, all we needed is an CMakeLists.txt
cmake_minimum_required(VERSION 2.8)
project(HELLO)
find_package(PythonLibs REQUIRED)
include_directories(${PYTHON_INCLUDE_DIRS})
add_executable(hello main.cpp)
In this file, we do not need to specify the path of python.

qmake

Then how about qmake ?A XXX.pro file can be written like this:
CONFIG  -= qt
CONFIG  += console
SOURCES += main.cpp
unix{
    CONFIG += link_pkgconfig
    PKGCONFIG += python
}

# NO! I hate following code
win32{
    INCLUDEPATH += D:\\Python27\\include
    LIBS += D:\\Python27\\libs\python27.lib
}
pkg_config can be used to extract infomation needed under Linux, but it does not works well under windows.
And finially, I try to get the home path of python from the register, which works very well.
win32:{
   PY_VERSIONS = 2.7 2.6 2.5 2.4
   for(PY_VERSION, PY_VERSIONS){
       system(reg query HKLM\\SOFTWARE\\Python\\PythonCore\\$$PY_VERSION\\InstallPath /ve) {
           PY_HOME = $$quote($$system(reg query HKLM\\SOFTWARE\\Python\\PythonCore\\$$PY_VERSION\\InstallPath /ve))
           PY_HOME ~= s/.*(\\w:.*)/\\1
           !exists($$PY_HOME\\include\\Python.h):next()
           INCLUDEPATH *= $$PY_HOME\\include

           PY_LIB_BASENAME = python$${PY_VERSION}
           PY_LIB_BASENAME ~= s/\\./
           CONFIG(debug, debug|release):PY_LIB_BASENAME = $${PY_LIB_BASENAME}_d
           LIBS *= $$PY_HOME\\libs\\$${PY_LIB_BASENAME}.lib
           message(Python$$PY_VERSION found at $$PY_HOME)
           break()
       }
   }
}

No comments: