Environment setup
Choose 1 from 2
1. Prepare 32-bit python and 32-bit mingw
2. Prepare 64-bit python and 64-bit mingw64
- 32-bit mingw download address: https://disk.baidu.com/s/1Z25NxrRuOsjOKWXddTNyeg Extraction code: dvgl
- 64-bit mingw64 download address: https://www.onlinedown.net/soft/10045442.htm
- Those who are capable can also download it directly from mingw’s official website: https://www.mingw-w64.org/
Set the path to g++.exe as an environment variable
- Take mingw64 as an example (32-bit is the same)
- Unzip the downloaded mingw64 above and unzip the files inside to your favorite path.
Set up a python environment (omitted)
After g++ and python are set up, you can start hello word!
Compile c++ code into exe program
- Create a new c_call_py.cpp
#include <stdlib.h>
#include <Python.h>
int main(int argc, char *argv[]){
Py_Initialize();
PyRun_SimpleString("print('hello world')\n");
Py_Finalize();
system("pause"); // 暂停
return 0;
}
- Open cmd (preferably run with administrator rights)
- Enter g++ c_call_py.cpp in cmd -I "My computer's python path\include" -L "My computer's python path/libs" -l My computer's python .lib -o test
- For example, my computer python3.8 inputs like this
- g++ c_call_py.cpp -I “C:\Program Files\Python38\include” -L"C:/Program Files/Python38/libs" -lpython38 -o test
-
Compiled and generated test.exe
-
Potential pitfalls you may encounter along the way
- Most of what you see on Baidu search is this command line: g++ main.cpp -I/usr/include/python3.5 -lpython3.5m -o test
- I've been stuck here for a long time. The call to the win environment is not suitable for this command at all.
- Unresolved external symbol __imp_Py_Initialize…
- The reason is that mingw and python are not the same 64 or 32. I initially called 64-bit python with 32-bit mingw, which caused this error.
- Most of what you see on Baidu search is this command line: g++ main.cpp -I/usr/include/python3.5 -lpython3.5m -o test