如何用Distutils替代CMake实现GLFW与Python C++扩展的链接?
将GLFW链接到Python C++扩展:CMake转Distutils的问题
我用CMake可以正常实现GLFW与Python C++扩展的链接,配置如下:
cmake_minimum_required(VERSION 3.0) project(Test) add_subdirectory(lib/glfw) add_executable(Test py_extend.cpp) target_include_directories(Test PRIVATE ${OPENGL_INCLUDE_DIR} ) target_link_libraries(Test PRIVATE ${OPENGL_LIBRARY} glfw )
但改用Distutils实现时出现编译错误,我的Distutils代码如下:
from distutils.core import setup, Extension from distutils.ccompiler import CCompiler, new_compiler our_compiler = new_compiler() our_compiler.add_include_dir("glfw") our_compiler.add_library("glfw") our_compiler.add_library_dir("lib/glfw") module1 = Extension('test', sources = ['py_extend.cpp', 'src/glfw_binder.cpp'], include_dirs=["include/glfw_binder.h"], libraries=["glfw"], library_dirs=["lib/glfw"] ) setup (name = 'python_test', version = '1.0', description = 'This is a demo package', ext_modules = [module1] )
执行python3 build.py build后报错:
python3 build.py build running build running build_ext building 'test' extension x86_64-linux-gnu-gcc -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -g -fwrapv -O2 -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -Iinclude/glfw_binder.h -I/usr/include/python3.10 -c py_extend.cpp -o build/temp.linux-x86_64-3.10/py_extend.o cc1plus: warning: include/glfw_binder.h: not a directory In file included from py_extend.cpp:4: ./include/glfw_binder.h:4:10: fatal error: GLFW/glfw3.h: No such file or directory 4 | #include <GLFW/glfw3.h> | ^~~~~~~~~~~~~~ compilation terminated. error: command '/usr/bin/x86_64-linux-gnu-gcc' failed with exit code 1
请问如何将上述CMake配置正确转换为Distutils代码?
问题分析与修正方案
你的Distutils代码存在几个关键问题,导致编译失败:
include_dirs传入了具体头文件而非目录- 缺少GLFW头文件的路径指定
- 创建的
our_compiler对象未被setup调用,属于冗余代码 - 未添加OpenGL库的链接依赖
修正后的Distutils代码如下:
from distutils.core import setup, Extension module1 = Extension('test', sources=['py_extend.cpp', 'src/glfw_binder.cpp'], # 指定头文件目录:自身binder头文件目录 + GLFW的include目录 include_dirs=["include", "lib/glfw/include"], # 链接GLFW与OpenGL库,对应CMake中的依赖 libraries=["glfw", "GL"], # 指定GLFW编译后库文件的所在目录 library_dirs=["lib/glfw/src"], # 显式指定C++编译标准,避免版本兼容问题 extra_compile_args=["-std=c++11"] ) setup(name='python_test', version='1.0', description='This is a demo package', ext_modules=[module1] )
关键修改说明:
- include_dirs:补充
lib/glfw/include以让编译器找到GLFW的头文件,同时将include/glfw_binder.h改为include(头文件所在目录)。 - libraries:添加
GL库,对应CMake中的${OPENGL_LIBRARY}依赖。 - library_dirs:调整为
lib/glfw/src,因为GLFW编译后的库文件默认生成在该目录下(若你的GLFW库路径不同,自行修改)。 - 删除冗余代码:移除未被使用的
our_compiler相关代码。 - extra_compile_args:显式指定C++标准,避免编译器默认标准过低引发的编译问题。
注意:执行构建前,需确保已通过CMake在lib/glfw目录下编译生成了GLFW库文件,否则Distutils会找不到glfw库。
内容的提问来源于stack exchange,提问作者Turgut
相关产品推荐
相关产品推荐

