cmake.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. """
  2. * Copyright (c) 2006-2025 RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2019-05-24 klivelinux first version
  9. * 2021-04-19 liukangcc add c++ support and libpath
  10. * 2021-06-25 Guozhanxin fix path issue
  11. * 2021-06-30 Guozhanxin add scons --target=cmake-armclang
  12. * 2022-03-16 liukangcc 通过 SCons生成 CMakefile.txt 使用相对路径
  13. * 2022-04-12 mysterywolf rtconfig.CROSS_TOOL->rtconfig.PLATFORM
  14. * 2022-04-29 SunJun8 默认开启生成编译数据库
  15. * 2024-03-18 wirano fix the issue of the missing link flags added in Sconscript
  16. * 2024-07-04 kaidegit Let cmake generator get more param from `rtconfig.py`
  17. * 2024-08-07 imi415 Updated CMake generator handles private macros, using OBJECT and INTERFACE libraries.
  18. * 2024-11-18 kaidegit fix processing groups with similar name
  19. * 2024-11-18 kaidegit fix missing some flags added in Sconscript
  20. """
  21. import os
  22. import sys
  23. import re
  24. import utils
  25. import rtconfig
  26. from utils import _make_path_relative
  27. from collections import defaultdict, Counter
  28. def GenerateCFiles(env, project, project_name):
  29. """
  30. Generate CMakeLists.txt files
  31. """
  32. info = utils.ProjectInfo(env)
  33. PROJECT_NAME = project_name if project_name != "project" else "rtthread"
  34. tool_path_conv = defaultdict(lambda : {"name":"", "path": ""})
  35. tool_path_conv_helper = lambda tool: {"name": tool, "path": os.path.join(rtconfig.EXEC_PATH, tool).replace('\\', "/")}
  36. tool_path_conv["CMAKE_C_COMPILER"] = tool_path_conv_helper(rtconfig.CC)
  37. if 'CXX' in dir(rtconfig):
  38. tool_path_conv["CMAKE_CXX_COMPILER"] = tool_path_conv_helper(rtconfig.CXX)
  39. tool_path_conv["CMAKE_ASM_COMPILER"] = tool_path_conv_helper(rtconfig.AS)
  40. tool_path_conv["CMAKE_AR"] = tool_path_conv_helper(rtconfig.AR)
  41. tool_path_conv["CMAKE_LINKER"] = tool_path_conv_helper(rtconfig.LINK)
  42. if rtconfig.PLATFORM in ['gcc']:
  43. tool_path_conv["CMAKE_SIZE"] = tool_path_conv_helper(rtconfig.SIZE)
  44. tool_path_conv["CMAKE_OBJDUMP"] = tool_path_conv_helper(rtconfig.OBJDUMP)
  45. tool_path_conv["CMAKE_OBJCOPY"] = tool_path_conv_helper(rtconfig.OBJCPY)
  46. elif rtconfig.PLATFORM in ['armcc', 'armclang']:
  47. tool_path_conv["CMAKE_FROMELF"] = tool_path_conv_helper(rtconfig.FROMELF)
  48. CC = tool_path_conv["CMAKE_C_COMPILER"]["path"]
  49. CXX = tool_path_conv["CMAKE_CXX_COMPILER"]["path"]
  50. AS = tool_path_conv["CMAKE_ASM_COMPILER"]["path"]
  51. AR = tool_path_conv["CMAKE_AR"]["path"]
  52. LINK = tool_path_conv["CMAKE_LINKER"]["path"]
  53. SIZE = tool_path_conv["CMAKE_SIZE"]["path"]
  54. OBJDUMP = tool_path_conv["CMAKE_OBJDUMP"]["path"]
  55. OBJCOPY = tool_path_conv["CMAKE_OBJCOPY"]["path"]
  56. FROMELF = tool_path_conv["CMAKE_FROMELF"]["path"]
  57. CFLAGS = env['CFLAGS'].replace('\\', "/").replace('\"', "\\\"")
  58. if 'CXXFLAGS' in dir(rtconfig):
  59. CXXFLAGS = env['CXXFLAGS'].replace('\\', "/").replace('\"', "\\\"")
  60. else:
  61. CXXFLAGS = CFLAGS
  62. AFLAGS = env['ASFLAGS'].replace('\\', "/").replace('\"', "\\\"")
  63. LFLAGS = env['LINKFLAGS'].replace('\\', "/").replace('\"', "\\\"")
  64. POST_ACTION = rtconfig.POST_ACTION
  65. # replace the tool name with the cmake variable
  66. for cmake_var, each_tool in tool_path_conv.items():
  67. tool_name = each_tool['name']
  68. if tool_name == "": continue
  69. if "win32" in sys.platform:
  70. while f"{tool_name}.exe" in POST_ACTION: # find the tool with `.exe` suffix first
  71. POST_ACTION = POST_ACTION.replace(tool_name, "string_to_replace")
  72. while tool_name in POST_ACTION:
  73. POST_ACTION = POST_ACTION.replace(tool_name, "string_to_replace")
  74. while "string_to_replace" in POST_ACTION:
  75. POST_ACTION = POST_ACTION.replace("string_to_replace", f"${{{cmake_var}}}")
  76. # replace the `$TARGET` with `${CMAKE_PROJECT_NAME}.elf`
  77. while "$TARGET" in POST_ACTION:
  78. POST_ACTION = POST_ACTION.replace("$TARGET", "${CMAKE_PROJECT_NAME}.elf")
  79. # add COMMAAND before each command
  80. POST_ACTION = POST_ACTION.split('\n')
  81. POST_ACTION = [each_line.strip() for each_line in POST_ACTION]
  82. POST_ACTION = [f"\tCOMMAND {each_line}" for each_line in POST_ACTION if each_line != '']
  83. POST_ACTION = "\n".join(POST_ACTION)
  84. if "win32" in sys.platform:
  85. CC += ".exe"
  86. if CXX != '':
  87. CXX += ".exe"
  88. AS += ".exe"
  89. AR += ".exe"
  90. LINK += ".exe"
  91. if rtconfig.PLATFORM in ['gcc']:
  92. SIZE += ".exe"
  93. OBJDUMP += ".exe"
  94. OBJCOPY += ".exe"
  95. elif rtconfig.PLATFORM in ['armcc', 'armclang']:
  96. FROMELF += ".exe"
  97. if not os.path.exists(CC) or not os.path.exists(AS) or not os.path.exists(AR) or not os.path.exists(LINK):
  98. print("'Cannot found toolchain directory, please check RTT_CC and RTT_EXEC_PATH'")
  99. sys.exit(-1)
  100. with open("CMakeLists.txt", "w") as cm_file:
  101. cm_file.write("CMAKE_MINIMUM_REQUIRED(VERSION 3.10)\n\n")
  102. cm_file.write("SET(CMAKE_SYSTEM_NAME Generic)\n")
  103. cm_file.write("SET(CMAKE_SYSTEM_PROCESSOR " + rtconfig.CPU +")\n")
  104. cm_file.write("#SET(CMAKE_VERBOSE_MAKEFILE ON)\n\n")
  105. cm_file.write("SET(CMAKE_EXPORT_COMPILE_COMMANDS ON)\n\n")
  106. cm_file.write("SET(CMAKE_C_COMPILER \""+ CC + "\")\n")
  107. cm_file.write("SET(CMAKE_ASM_COMPILER \""+ AS + "\")\n")
  108. cm_file.write("SET(CMAKE_C_FLAGS \""+ CFLAGS + "\")\n")
  109. cm_file.write("SET(CMAKE_ASM_FLAGS \""+ AFLAGS + "\")\n")
  110. cm_file.write("SET(CMAKE_C_COMPILER_WORKS TRUE)\n\n")
  111. if CXX != '':
  112. cm_file.write("SET(CMAKE_CXX_COMPILER \""+ CXX + "\")\n")
  113. cm_file.write("SET(CMAKE_CXX_FLAGS \""+ CXXFLAGS + "\")\n")
  114. cm_file.write("SET(CMAKE_CXX_COMPILER_WORKS TRUE)\n\n")
  115. if rtconfig.PLATFORM in ['gcc']:
  116. cm_file.write("SET(CMAKE_OBJCOPY \""+ OBJCOPY + "\")\n")
  117. cm_file.write("SET(CMAKE_SIZE \""+ SIZE + "\")\n\n")
  118. elif rtconfig.PLATFORM in ['armcc', 'armclang']:
  119. cm_file.write("SET(CMAKE_FROMELF \""+ FROMELF + "\")\n\n")
  120. LINKER_FLAGS = ''
  121. LINKER_LIBS = ''
  122. if rtconfig.PLATFORM in ['gcc']:
  123. LINKER_FLAGS += '-T'
  124. elif rtconfig.PLATFORM in ['armcc', 'armclang']:
  125. LINKER_FLAGS += '--scatter'
  126. for group in project:
  127. if 'LIBPATH' in group.keys():
  128. for f in group['LIBPATH']:
  129. LINKER_LIBS += ' --userlibpath ' + f.replace("\\", "/")
  130. for group in project:
  131. if 'LIBS' in group.keys():
  132. for f in group['LIBS']:
  133. LINKER_LIBS += ' ' + f.replace("\\", "/") + '.lib'
  134. cm_file.write("SET(CMAKE_EXE_LINKER_FLAGS \""+ re.sub(LINKER_FLAGS + '(\s*)', LINKER_FLAGS + ' ${CMAKE_SOURCE_DIR}/', LFLAGS) + LINKER_LIBS + "\")\n\n")
  135. # get the c/cpp standard version from compilation flags
  136. # not support the version with alphabet in `-std` param yet
  137. pattern = re.compile('-std=[\w+]+')
  138. c_standard = 11
  139. if '-std=' in CFLAGS:
  140. c_standard = re.search(pattern, CFLAGS).group(0)
  141. c_standard = "".join([each for each in c_standard if each.isdigit()])
  142. else:
  143. print(f"Cannot find the param of the c standard in build flag, set to default {c_standard}")
  144. cm_file.write(f"SET(CMAKE_C_STANDARD {c_standard})\n")
  145. if CXX != '':
  146. cpp_standard = 17
  147. if '-std=' in CXXFLAGS:
  148. cpp_standard = re.search(pattern, CXXFLAGS).group(0)
  149. cpp_standard = "".join([each for each in cpp_standard if each.isdigit()])
  150. else:
  151. print(f"Cannot find the param of the cpp standard in build flag, set to default {cpp_standard}")
  152. cm_file.write(f"SET(CMAKE_CXX_STANDARD {cpp_standard})\n")
  153. cm_file.write('\n')
  154. cm_file.write(f"PROJECT({PROJECT_NAME} C {'CXX' if CXX != '' else ''} ASM)\n")
  155. cm_file.write('\n')
  156. cm_file.write("INCLUDE_DIRECTORIES(\n")
  157. for i in info['CPPPATH']:
  158. # use relative path
  159. path = _make_path_relative(os.getcwd(), i)
  160. cm_file.write( "\t" + path.replace("\\", "/") + "\n")
  161. cm_file.write(")\n\n")
  162. cm_file.write("ADD_DEFINITIONS(\n")
  163. for i in info['CPPDEFINES']:
  164. cm_file.write("\t-D" + i + "\n")
  165. cm_file.write(")\n\n")
  166. libgroups = []
  167. interfacelibgroups = []
  168. for group in project:
  169. if group['name'] == 'Applications':
  170. continue
  171. # When a group is provided without sources, add it to the <INTERFACE> library list
  172. if len(group['src']) == 0:
  173. interfacelibgroups.append(group)
  174. else:
  175. libgroups.append(group)
  176. # Process groups whose names differ only in capitalization.
  177. # (Groups have same name should be merged into one before)
  178. for group in libgroups:
  179. group['alias'] = group['name'].lower()
  180. names = [group['alias'] for group in libgroups]
  181. counter = Counter(names)
  182. names = [name for name in names if counter[name] > 1]
  183. for group in libgroups:
  184. if group['alias'] in names:
  185. counter[group['alias']] -= 1
  186. group['alias'] = f"{group['name']}_{counter[group['alias']]}"
  187. print(f"Renamed {group['name']} to {group['alias']}")
  188. group['name'] = group['alias']
  189. cm_file.write("# Library source files\n")
  190. for group in project:
  191. cm_file.write("SET(RT_{:s}_SOURCES\n".format(group['name'].upper()))
  192. for f in group['src']:
  193. # use relative path
  194. path = _make_path_relative(os.getcwd(), os.path.normpath(f.rfile().abspath))
  195. cm_file.write( "\t" + path.replace("\\", "/") + "\n" )
  196. cm_file.write(")\n\n")
  197. cm_file.write("# Library search paths\n")
  198. for group in libgroups + interfacelibgroups:
  199. if not 'LIBPATH' in group.keys():
  200. continue
  201. if len(group['LIBPATH']) == 0:
  202. continue
  203. cm_file.write("SET(RT_{:s}_LINK_DIRS\n".format(group['name'].upper()))
  204. for f in group['LIBPATH']:
  205. cm_file.write("\t"+ f.replace("\\", "/") + "\n" )
  206. cm_file.write(")\n\n")
  207. cm_file.write("# Library local macro definitions\n")
  208. for group in libgroups:
  209. if not 'LOCAL_CPPDEFINES' in group.keys():
  210. continue
  211. if len(group['LOCAL_CPPDEFINES']) == 0:
  212. continue
  213. cm_file.write("SET(RT_{:s}_DEFINES\n".format(group['name'].upper()))
  214. for f in group['LOCAL_CPPDEFINES']:
  215. cm_file.write("\t"+ f.replace("\\", "/") + "\n" )
  216. cm_file.write(")\n\n")
  217. cm_file.write("# Library dependencies\n")
  218. for group in libgroups + interfacelibgroups:
  219. if not 'LIBS' in group.keys():
  220. continue
  221. if len(group['LIBS']) == 0:
  222. continue
  223. cm_file.write("SET(RT_{:s}_LIBS\n".format(group['name'].upper()))
  224. for f in group['LIBS']:
  225. cm_file.write("\t"+ "{}\n".format(f.replace("\\", "/")))
  226. cm_file.write(")\n\n")
  227. cm_file.write("# Libraries\n")
  228. for group in libgroups:
  229. cm_file.write("ADD_LIBRARY(rtt_{:s} OBJECT ${{RT_{:s}_SOURCES}})\n"
  230. .format(group['name'], group['name'].upper()))
  231. cm_file.write("\n")
  232. cm_file.write("# Interface libraries\n")
  233. for group in interfacelibgroups:
  234. cm_file.write("ADD_LIBRARY(rtt_{:s} INTERFACE)\n".format(group['name']))
  235. cm_file.write("\n")
  236. cm_file.write("# Private macros\n")
  237. for group in libgroups:
  238. if not 'LOCAL_CPPDEFINES' in group.keys():
  239. continue
  240. if len(group['LOCAL_CPPDEFINES']) == 0:
  241. continue
  242. cm_file.write("TARGET_COMPILE_DEFINITIONS(rtt_{:s} PRIVATE ${{RT_{:s}_DEFINES}})\n"
  243. .format(group['name'], group['name'].upper()))
  244. cm_file.write("\n")
  245. cm_file.write("# Interface library search paths\n")
  246. if rtconfig.PLATFORM in ['gcc']:
  247. for group in libgroups:
  248. if not 'LIBPATH' in group.keys():
  249. continue
  250. if len(group['LIBPATH']) == 0:
  251. continue
  252. cm_file.write("TARGET_LINK_DIRECTORIES(rtt_{:s} INTERFACE ${{RT_{:s}_LINK_DIRS}})\n"
  253. .format(group['name'], group['name'].upper()))
  254. for group in libgroups:
  255. if not 'LIBS' in group.keys():
  256. continue
  257. if len(group['LIBS']) == 0:
  258. continue
  259. cm_file.write("TARGET_LINK_LIBRARIES(rtt_{:s} INTERFACE ${{RT_{:s}_LIBS}})\n"
  260. .format(group['name'], group['name'].upper()))
  261. cm_file.write("\n")
  262. cm_file.write("ADD_EXECUTABLE(${CMAKE_PROJECT_NAME}.elf ${RT_APPLICATIONS_SOURCES})\n")
  263. cm_file.write("TARGET_LINK_LIBRARIES(${CMAKE_PROJECT_NAME}.elf\n")
  264. for group in libgroups + interfacelibgroups:
  265. cm_file.write("\trtt_{:s}\n".format(group['name']))
  266. cm_file.write(")\n\n")
  267. cm_file.write("ADD_CUSTOM_COMMAND(TARGET ${CMAKE_PROJECT_NAME}.elf POST_BUILD \n" + POST_ACTION + '\n)\n')
  268. # auto inclue `custom.cmake` for user custom settings
  269. custom_cmake = \
  270. '''
  271. # if custom.cmake is exist, add it
  272. if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/custom.cmake)
  273. include(${CMAKE_CURRENT_SOURCE_DIR}/custom.cmake)
  274. endif()
  275. '''
  276. custom_cmake = custom_cmake.split('\n')
  277. custom_cmake = [each.strip() for each in custom_cmake]
  278. custom_cmake = "\n".join(custom_cmake)
  279. cm_file.write(custom_cmake)
  280. return
  281. def CMakeProject(env, project, project_name):
  282. print('Update setting files for CMakeLists.txt...')
  283. GenerateCFiles(env, project, project_name)
  284. print('Done!')
  285. return