-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcreate_Makefile.py
189 lines (166 loc) · 7.46 KB
/
create_Makefile.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
#!/bin/python3
import os, functools, subprocess, sys
def target_sort(a, b):
if a == b:
return 0
# all target is first
if a == 'all':
return -1
if b == 'all':
return 1
# .PHONY is last
if a == '.PHONY':
return 1
if b == '.PHONY':
return -1
# Sort targets creating files after meta-targets
if a[0] == '$':
if b[0] != '$':
return 1
elif b[0] == '$':
return -1
if a < b:
return -1
if a > b:
return 1
def all_targets_so_far(depends, operations):
return sorted(set(depends.keys()) | set(operations.keys()), key=functools.cmp_to_key(target_sort))
if len(sys.argv) == 1 or sys.argv[1] not in ['gcc', 'clang']:
print('Specify a compiler ("gcc" or "clang")')
sys.exit(1)
program_name = 'genetic_chess'
final_targets = ["release", "debug"]
depends = dict()
depends['all'] = ["docs"] + final_targets
depends['clean'] = (f"clean_{target}" for target in depends['all'])
depends["docs"] = ["user_manual", "code_docs"]
depends['clean_docs'] = (f"clean_{target}" for target in depends['docs'])
obj_dest = dict()
operations = dict()
bins = dict()
link_dirs = dict()
depends["code_docs"] = ['$(DOC_INDEX)']
operations['$(DOC_INDEX)'] = ['doxygen']
depends['$(DOC_INDEX)'] = ["Doxyfile", "$(ALL_SOURCES)"]
user_manual = 'doc/reference.pdf'
user_manual_tex = f'{os.path.splitext(user_manual)[0]}.tex'
user_manual_var = '$(USER_MANUAL)'
depends["user_manual"] = [user_manual_var]
depends[user_manual_var] = [
user_manual_tex,
'gene_pool_config_example.txt',
'genome_example.txt',
'doc/game-endings-log-plot.png',
'doc/divergence-example.png',
'doc/game_length_log_norm_distribution.png',
'doc/pawn-crash-strength-plot.png',
'doc/piece-strength-with-king-plot.png',
'doc/win-lose-plot.png']
operations[user_manual_var] = [f'latexmk -synctex=1 -pdf -cd {user_manual_tex}', f'touch {user_manual_var}']
for target in final_targets:
out_variable = f"$({target.upper()}_OUT)"
all_objects = f"$({target.upper()}_OBJ)"
bin_dest = f"$({target.upper()}_BIN_DIR)"
operations[out_variable] = [f"mkdir -p {bin_dest}",
' '.join(["$(LD)",
"-o", out_variable,
all_objects,
"$(LDFLAGS)",
f"$({target.upper()}_LDFLAGS)",
"$(CFLAGS)",
f"$({target.upper()}CFLAGS)"])]
link_dirs[target] = os.path.join('bin', target)
link_dir_variable = f"$({target.upper()}_LINK_DIR)"
operations[os.path.join(link_dir_variable, '$(BIN)')] = [f'mkdir -p {link_dir_variable}',
f'ln -sf -t {link_dir_variable} `realpath {out_variable}`',
f'touch {out_variable}']
depends[os.path.join(link_dir_variable, '$(BIN)')] = [out_variable]
depends[target] = [out_variable, os.path.join(link_dir_variable, '$(BIN)')]
depends[out_variable] = [all_objects]
obj_dest[target] = f"$({target.upper()}_OBJ_DIR)"
operations[f'clean_{target}'] = [f"rm -rf {obj_dest[target]} {bin_dest}"]
bins[target] = os.path.join(bin_dest, '$(BIN)')
depends[f'test_{target}'] = [target]
operations[f'test_{target}'] = [f'{bins[target]} -{opt}' for opt in ['test', 'perft', 'speed']]
operations['clean_code_docs'] = ['rm -rf $(DOC_DIR)']
operations['clean_user_manual'] = [f'latexmk -C -cd {user_manual_tex}']
depends['test'] = [f'test_{x}' for x in final_targets]
depends['.PHONY'] = [t for t in all_targets_so_far(depends, operations) if not t.startswith('$')]
options_list = dict()
linker_options = dict()
base_options = [
"-std=c++23",
"-Wshadow",
"-Wcast-align",
"-Wundef",
"-Wfloat-equal",
"-Wunreachable-code",
"-pedantic",
"-Wextra",
"-Wall",
"-Werror",
"-Isrc"]
base_linker_options = ["-pthread"]
linker_options['debug'] = []
linker_options['release'] = ['-flto']
options_list['debug'] = ["-g"]
options_list['release'] = ["-O3", "-DNDEBUG", "-march=native", "-mtune=native"]
system = sys.argv[1]
if system == 'gcc':
compiler = 'g++-14'
base_options.extend([
"-Wmain",
"-Wno-maybe-uninitialized",
"-Wconversion"])
elif system == 'clang':
compiler = 'clang++'
linker_options['debug'] = ["-fsanitize=undefined", "-fsanitize=integer"]
options_list['debug'].extend(["-Og"] + linker_options['debug'])
base_options.extend([
"-Wnon-virtual-dtor",
"-Wredundant-decls",
"-Wmissing-declarations",
"-Wmissing-include-dirs",
"-Wunused-exception-parameter",
"-Wswitch",
"-Wfloat-conversion"])
all_sources = []
for target in final_targets:
for (dirpath, dirnames, filenames) in os.walk(os.getcwd()):
dirpath = os.path.relpath(dirpath)
if dirpath == '.': dirpath = ''
for source_file in [os.path.join(dirpath, fn) for fn in filenames]:
if source_file.endswith('.h') or source_file.endswith('.cpp'):
all_sources.append(source_file)
if not source_file.endswith('.cpp'):
continue
obj_file = os.path.join(obj_dest[target], f"{os.path.splitext(source_file)[0]}.o")
operations[obj_file] = [f"mkdir -p {os.path.dirname(obj_file)}",
f"$(CXX) $(CFLAGS) $(LDFLAGS) $({target.upper()}_CFLAGS) $({target.upper()}_LDFLAGS) -c {source_file} -o {obj_file}"]
compiler_command = [compiler] + base_options + options_list[target] + ['-MM', source_file]
compile_depends = subprocess.check_output(compiler_command).decode('ascii').split(':', 1)[1].split()
depends[obj_file] = sorted(list(set(d for d in compile_depends if d != '\\')))
with open("Makefile", 'w') as make_file:
make_file.write(f"BIN = {program_name}\n")
make_file.write(f"CXX = {compiler}\n")
make_file.write(f"LD = {compiler}\n\n")
make_file.write(f"CFLAGS = {' '.join(base_options)}\n")
make_file.write(f"LDFLAGS = {' '.join(base_linker_options)}\n\n")
make_file.write(f"DOC_DIR = {os.path.join('doc', 'doxygen', 'html')}\n")
make_file.write(f"DOC_INDEX = {os.path.join('$(DOC_DIR)', 'index.html')}\n")
make_file.write(f"ALL_SOURCES = {' '.join(all_sources)}\n\n")
make_file.write(f"USER_MANUAL = {user_manual}\n\n")
for target in final_targets:
make_file.write(f"{target.upper()}_BIN_DIR = bin/{system}/{target}\n")
make_file.write(f"{target.upper()}_OUT = {bins[target]}\n")
make_file.write(f"{target.upper()}_LINK_DIR = {link_dirs[target]}\n")
make_file.write(f"{target.upper()}_OBJ_DIR = obj/{system}/{target}\n")
make_file.write(f"{target.upper()}_OBJ = ")
make_file.write(' '.join([x for x in all_targets_so_far(depends, operations) if x.endswith('.o') and x.startswith(f"$({target.upper()}")]))
make_file.write('\n')
make_file.write(f"{target.upper()}_CFLAGS = {' '.join(options_list[target])}\n")
make_file.write(f"{target.upper()}_LDFLAGS = {' '.join(linker_options[target])}\n\n")
for target in all_targets_so_far(depends, operations):
make_file.write(f"{target} : {' '.join(depends.get(target, []))}\n")
make_file.write("\n".join([f"\t{x}" for x in operations.get(target, [])]))
make_file.write('\n\n')