繁体   English   中英

如何在 Windows 上编译包含 Python.h 的 C 程序?

[英]How do I compile a C program which includes Python.h on Windows?

我正在尝试学习如何将 Python 解释器嵌入到我的 C/C++ 程序中。

我喜欢这个概念,因为它可以让我在运行时扩展 C 程序,并使用户能够编写自定义脚本/插件。

Detailed instruction on embedding Python in C is provided at: https://docs.python.org/3/extending/embedding.html

我正在使用 Python 文档中提供的示例代码来找出所涉及的机制:

embedded.c

#include <Python.h>

int
main(int argc, char *argv[])
{
  Py_SetProgramName(argv[0]);  /* optional but recommended */
  Py_Initialize();
  PyRun_SimpleString("from time import time,ctime\n"
                     "print 'Today is',ctime(time())\n");
  Py_Finalize();
  return 0;
}

问题是我不知道如何使用 gcc 在 Windows 上编译它。

C:\Users\user\embedded_python> gcc embedded.c
embedded.c:2:10: fatal error: Python.h: No such file or directory
 #include <Python.h>
          ^~~~~~~~~~
compilation terminated.

我认为问题是我需要链接到 Python.h 文件,但我似乎无法正确获取编译器标志:

C:\Users\user\Desktop\embedded_python>gcc -IC:\Users\user\AppData\Local\Programs\Python\Python38 -lPython38 embedded.c
embedded.c:2:10: fatal error: Python.h: No such file or directory
 #include <Python.h>
          ^~~~~~~~~~
compilation terminated.

我怎样才能让这个程序在 Windows 上编译(最好使用 gcc/g++ 以避免 Visual Studio 膨胀)?

在 Linux 中,但我想如果你从 windows 激活你的Bash并可以解决问题。 首先你必须安装python3-dev

然后使用您的文件所在的命令行进行编译(测试是您的文件名)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM