python编译成c 调用_如何使用Cython将Python 3编译为C

I'm trying to convert a Python 3 script into C and then compile that C file into an executable.

I have this simple python script:

def greet(name = ""):

print("Hello {0}".format(name if len(name) > 0 else "World"))

greet("Mango")

I've converted this script into C using:

cython greet.py -o greet.c

Then I've compiled the C file using:

cc greet.c -o greet

After I entered the last command I got the error:

fatal error: Python.h: No such file or directory compilation terminated.

After I got the error I went back and realised that I was using Python3 and that I had forgot the "3" after "cython".

So re-compiled the python script using:

cython3 greet.py -o greet.c

Then attempted to re-compile the C file using:

cc greet.c -o greet

Again this failed and threw the same error so I went searching on SO and Google and found these questions:

None of these answers in these questions work.

I've made sure that I have installed cython all of the correct dependencies using apt-get install and pip install sadly thought it still does not seem to work.

解决方案

Check the documentation. It's not enough to do gcc x.c -o x.

There's a lot more to it, but a direct answer is:

Compiling your .c files will vary depending on your operating system. Python documentation for writing extension modules should have some details for your system. Here we give an example on a Linux system:

$ gcc -shared -pthread -fPIC -fwrapv -O2 -Wall -fno-strict-aliasing

-I/usr/include/python2.7 -o yourmod.so yourmod.c

Of course in your situation it's going to be something closer to -I/usr/include/python3.4, or even $(pkg-config --libs --cflags python3). And you're not building with -shared, because you want an executable.

Shortest "this has to work" set of commands is:

cython3 --embed greet.py -o greet.c

gcc $(pkg-config --libs --cflags python3) greet.c -o greet

You need to install pkg-config if it's missing.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值