自动生成make文件.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Mon Jun 24 11:03:47 2024
  4. @author: lijinwen
  5. @mail: ljwcoke@hotmail.com
  6. """
  7. import os
  8. def scan_files(root_dir):
  9. """
  10. 扫描指定目录下的所有 .cc 和 .h 文件
  11. """
  12. cc_files = []
  13. h_files = []
  14. for root, dirs, files in os.walk(root_dir):
  15. for file in files:
  16. if file.endswith(".cc"):
  17. cc_files.append(os.path.join(root, file))
  18. elif file.endswith(".h"):
  19. h_files.append(os.path.join(root, file))
  20. return cc_files, h_files
  21. def generate_makefile(cc_files, output_dir):
  22. """
  23. 根据 .cc 文件生成 Makefile,并将所有输出文件放在指定的 output 目录
  24. """
  25. if not os.path.exists(output_dir):
  26. os.makedirs(output_dir)
  27. with open(os.path.join(output_dir, "Makefile"), "w") as f:
  28. f.write("CXX = g++\n")
  29. f.write("CXXFLAGS = -Wall -g -shared\n") # 使用 -shared 标志生成共享库
  30. obj_files = [os.path.join("output", os.path.splitext(os.path.relpath(file, output_dir))[0] + ".o") for file in cc_files]
  31. f.write("OBJS = " + " ".join(obj_files) + "\n\n")
  32. f.write("TARGET = output/ProtocolDecoder.dll\n\n")
  33. f.write("all: $(TARGET)\n\n")
  34. f.write("$(TARGET): $(OBJS)\n")
  35. f.write("\t$(CXX) $(CXXFLAGS) -o $@ $^\n\n")
  36. for cc_file in cc_files:
  37. obj_file = os.path.join("output", os.path.splitext(os.path.relpath(cc_file, output_dir))[0] + ".o")
  38. f.write(f"{obj_file}: {os.path.relpath(cc_file, output_dir)}\n")
  39. f.write(f"\t$(CXX) $(CXXFLAGS) -c {os.path.relpath(cc_file, output_dir)} -o {obj_file}\n\n")
  40. f.write("clean:\n")
  41. f.write("\trm -f $(OBJS) $(TARGET)\n")
  42. if __name__ == "__main__":
  43. root_dir = "./" # 修改为你的项目路径
  44. output_dir = "./" # 修改为Makefile生成的路径
  45. cc_files, h_files = scan_files(root_dir)
  46. generate_makefile(cc_files, output_dir)