在Mac OS 环境下使用C++ 开发Python扩展时,需要引入Python.h 文件。
我的python环境比较多,有自己装的3.9和3.11,还有系统自带的2.7 ,还有使用brew安装的3.11。
使用自己安装的版本,目前还没走通,但是使用brew安装的3.11通过以下配置,完美运行
在CMakeLists.txt 文件配置如下:
其中 需要注意的点:
1.find_package Python版本要精确
2.target_link_libraries 填写的为 项目名(project 的内容)+ Python3_LIBRARIES
cmake_minimum_required(VERSION 3.24)
project(cpythonstudy)
set(CMAKE_CXX_STANDARD 17)
add_executable(cpythonstudy main.cpp)
#link_libraries(/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib)
#set(Python3_ROOT_DIR "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9")
find_package(Python3 3.11 COMPONENTS Interpreter Development REQUIRED)
if (Python3_FOUND)
message("Python include directory: " ${Python3_INCLUDE_DIRS})
message("Python version is: " ${Python3_VERSION})
include_directories(${Python3_INCLUDE_DIRS})
target_link_libraries(cpythonstudy ${Python3_LIBRARIES})
# link_libraries( ${Python3_LIBRARIES})/
endif (Python3_FOUND)
通过以上配置,代码可以运行通过
#include <iostream>
#include <Python.h>
using namespace std;
int main() {
Py_Initialize();
PyRun_SimpleString("print(1)");
Py_Finalize();
std::cout << "Hello, World!" << std::endl;
return 0;
}