python 辅助makefile 编译 摘要本文介绍如何通过 Python 脚本自动生成跨平台兼容的 Makefile 编译文件。由于不同操作系统及 Shell 终端对 Makefile 的语法支持存在差异手动维护兼容性较为繁琐因此作者提供了一套 Python 工具用于自动扫描项目中的 .c 和 .h 文件并生成对应的源文件列表与头文件目录从而快速构建 Makefile提升编译配置效率。Makefile 的编译文件在不同操作系统下不同我们可以通过识别操作系统对其进行兼容。在 Windows 操作系统对于不同 Shell 终端也会不同。这些对于我们编写一个兼容所有情况的 Makefile 文件来说会面临很多的困难。为了快速搞定 Makefile 文件我们可以使用 Python 获取所有的 .c 和 .h 文件自己生成 Makefile 内容进行编译。from pathlib import Path,PurePath,PureWindowsPath,PosixPath,PurePosixPath,WindowsPath def get_child_dir(dir, styleposix): # win posix ret [] for child in dir.glob(**/): if styleposix: ret.append( str(PurePosixPath(child)) ) else: ret.append( str(child) ) return ret def get_C_SOURCES(dirs ): ret[] for dir in dirs: ret.append( C_SOURCES $(wildcard *.c str(dir) /*.c)) return ret def get_C_INCLUDES(dirs): ret[] for dir in dirs: ret.append( C_INCLUDES -I str(dir) ) return ret def get_C_CPP_ProPerties(dirs): ret[] for dir in dirs: ret.append( \${workspaceFolder}/ str(dir) \, ) return ret if __name__ __main__: target_dir ( Middlewares,Third_Party, lvgl) dir Path() dir dir.joinpath(*target_dir) dirs get_child_dir(dir) c_makefile_statements get_C_SOURCES(dirs) for i in c_makefile_statements: print(i) h_makefile_statements get_C_INCLUDES(dirs) for i in h_makefile_statements: print(i) # c_cpp_property_statements get_C_CPP_ProPerties(dirs) # for i in c_cpp_property_statements: # print(i)以上脚本可以自动生成需要编译的源文件以及所有需要包含的头文件目录。快速构建 Makefile 文件。