摘要:本文介绍如何通过 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, style="posix"): # win posix ret = [] for child in dir.glob('**/'): if style=="posix": 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 文件。