[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

library file that is generated when Python is compiled, not the Python source code
standard library.


Today, everything in Python that you need in C is compiled into a single Python library
file when the interpreter is built (e.g., libpython3.1.dll on Cygwin). The program’s
main function comes from your C code, and depending on your platform and the ex-
tensions installed in your Python, you may also need to link any external libraries ref-
erenced by the Python library.


Assuming no extra extension libraries are needed, Example 20-24 is a minimal makefile
for building the C program in Example 20-23 under Cygwin on Windows. Again,
makefile details vary per platform, but see Python manuals for hints. This makefile uses
the Python include-files path to find Python.h in the compile step and adds the Python
library file to the final link step to make API calls available to the C program.


Example 20-24. PP4E\Integrate\Embed\Basics\makefile.1


a Cygwin makefile that builds a C executable that embeds


Python, assuming no external module libs must be linked in;


uses Python header files, links in the Python lib file;


both may be in other dirs (e.g., /usr) in your install;


PYLIB = /usr/local/bin
PYINC = /usr/local/include/python3.1


embed-simple: embed-simple.o
gcc embed-simple.o -L$(PYLIB) -lpython3.1 -g -o embed-simple


embed-simple.o: embed-simple.c
gcc embed-simple.c -c -g -I$(PYINC)


To build a program with this file, launch make on it as usual (as before, make sure
indentation in rules is tabs in your copy of this makefile):


.../PP4E/Integrate/Embed/Basics$ make -f makefile.1
gcc embed-simple.c -c -g -I/usr/local/include/python3.1
gcc embed-simple.o -L/usr/local/bin -lpython3.1 -g -o embed-simple

Things may not be quite this simple in practice, though, at least not without some
coaxing. The makefile in Example 20-25 is the one I actually used to build all of this
section’s C programs on Cygwin.


Example 20-25. PP4E\Integrate\Embed\Basics\makefile.basics


cygwin makefile to build all 5 basic embedding examples at once


PYLIB = /usr/local/bin
PYINC = /usr/local/include/python3.1


BASICS = embed-simple.exe \
embed-string.exe \
embed-object.exe \
embed-dict.exe \


1520 | Chapter 20: Python/C Integration

Free download pdf