windows: use _WIN32 define everywhere
[platform/upstream/ninja.git] / configure.py
1 #!/usr/bin/env python
2 #
3 # Copyright 2001 Google Inc. All Rights Reserved.
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 #     http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 """Script that generates the build.ninja for ninja itself.
18
19 Projects that use ninja themselves should either write a similar script
20 or use a meta-build system that supports Ninja output."""
21
22 from optparse import OptionParser
23 import os
24 import sys
25 sys.path.insert(0, 'misc')
26
27 import ninja_syntax
28
29 parser = OptionParser()
30 platforms = ['linux', 'freebsd', 'mingw', 'windows']
31 profilers = ['gmon', 'pprof']
32 parser.add_option('--platform',
33                   help='target platform (' + '/'.join(platforms) + ')',
34                   choices=platforms)
35 parser.add_option('--host',
36                   help='host platform (' + '/'.join(platforms) + ')',
37                   choices=platforms)
38 parser.add_option('--debug', action='store_true',
39                   help='enable debugging flags',)
40 parser.add_option('--profile', metavar='TYPE',
41                   choices=profilers,
42                   help='enable profiling (' + '/'.join(profilers) + ')',)
43 parser.add_option('--with-gtest', metavar='PATH',
44                   help='use gtest unpacked in directory PATH')
45 parser.add_option('--with-python', metavar='EXE',
46                   help='use EXE as the Python interpreter',
47                   default=os.path.basename(sys.executable))
48 (options, args) = parser.parse_args()
49 if args:
50     print 'ERROR: extra unparsed command-line arguments:', args
51     sys.exit(1)
52
53 platform = options.platform
54 if platform is None:
55     platform = sys.platform
56     if platform.startswith('linux'):
57         platform = 'linux'
58     elif platform.startswith('freebsd'):
59         platform = 'freebsd'
60     elif platform.startswith('mingw'):
61         platform = 'mingw'
62     elif platform.startswith('win'):
63         platform = 'windows'
64 host = options.host or platform
65
66 BUILD_FILENAME = 'build.ninja'
67 buildfile = open(BUILD_FILENAME, 'w')
68 n = ninja_syntax.Writer(buildfile)
69 n.comment('This file is used to build ninja itself.')
70 n.comment('It is generated by ' + os.path.basename(__file__) + '.')
71 n.newline()
72
73 n.comment('The arguments passed to configure.py, for rerunning it.')
74 n.variable('configure_args', ' '.join(sys.argv[1:]))
75 n.newline()
76
77 objext = '.o'
78 if platform == 'windows':
79     objext = '.obj'
80
81 def src(filename):
82     return os.path.join('src', filename)
83 def built(filename):
84     return os.path.join('$builddir', filename)
85 def doc(filename):
86     return os.path.join('doc', filename)
87 def cc(name, **kwargs):
88     return n.build(built(name + objext), 'cxx', src(name + '.c'), **kwargs)
89 def cxx(name, **kwargs):
90     return n.build(built(name + objext), 'cxx', src(name + '.cc'), **kwargs)
91 def binary(name):
92     if platform in ('mingw', 'windows'):
93         return name + '.exe'
94     return name
95
96 n.variable('builddir', 'build')
97 if platform == 'windows':
98     n.variable('cxx', 'cl')
99     n.variable('ar', 'link')
100 else:
101     n.variable('cxx', os.environ.get('CXX', 'g++'))
102     n.variable('ar', os.environ.get('AR', 'ar'))
103
104 if platform == 'windows':
105     cflags = ['/nologo', '/Zi', '/W4', '/WX', '/wd4530', '/wd4100', '/wd4706',
106               '/wd4512', '/wd4800', '/wd4702',
107               '/D_CRT_SECURE_NO_WARNINGS',
108               "/DNINJA_PYTHON=\"%s\"" % (options.with_python,)]
109     ldflags = ['/DEBUG', '/libpath:$builddir']
110     if not options.debug:
111         cflags += ['/Ox', '/DNDEBUG', '/GL']
112         ldflags += ['/LTCG', '/OPT:REF', '/OPT:ICF']
113 else:
114     cflags = ['-g', '-Wall', '-Wextra',
115               '-Wno-deprecated',
116               '-Wno-unused-parameter',
117               '-fno-exceptions',
118               '-fvisibility=hidden', '-pipe',
119               "'-DNINJA_PYTHON=\"%s\"'" % (options.with_python,)]
120     if options.debug:
121         cflags += ['-D_GLIBCXX_DEBUG', '-D_GLIBCXX_DEBUG_PEDANTIC']
122     else:
123         cflags += ['-O2', '-DNDEBUG']
124     ldflags = ['-L$builddir']
125 libs = []
126
127 if platform == 'mingw':
128     cflags.remove('-fvisibility=hidden');
129     ldflags.append('-static')
130 elif platform == 'windows':
131     pass
132 else:
133     if options.profile == 'gmon':
134         cflags.append('-pg')
135         ldflags.append('-pg')
136     elif options.profile == 'pprof':
137         libs.append('-lprofiler')
138
139 if 'CFLAGS' in os.environ:
140     cflags.append(os.environ['CFLAGS'])
141 n.variable('cflags', ' '.join(cflags))
142 if 'LDFLAGS' in os.environ:
143     ldflags.append(os.environ['LDFLAGS'])
144 n.variable('ldflags', ' '.join(ldflags))
145 n.newline()
146
147 if platform == 'windows':
148     n.rule('cxx',
149         command='$cxx $cflags -c $in /Fo$out',
150         depfile='$out.d',
151         description='CXX $out')
152 else:
153     n.rule('cxx',
154         command='$cxx -MMD -MF $out.d $cflags -c $in -o $out',
155         depfile='$out.d',
156         description='CXX $out')
157 n.newline()
158
159 if host == 'windows':
160     n.rule('ar',
161            command='lib /nologo /ltcg /out:$out $in',
162            description='LIB $out')
163 elif host == 'mingw':
164     n.rule('ar',
165            command='cmd /c $ar cqs $out.tmp $in && move /Y $out.tmp $out',
166            description='AR $out')
167 else:
168     n.rule('ar',
169            command='rm -f $out && $ar crs $out $in',
170            description='AR $out')
171 n.newline()
172
173 if platform == 'windows':
174     n.rule('link',
175         command='$cxx $in $libs /nologo /link $ldflags /out:$out',
176         description='LINK $out')
177 else:
178     n.rule('link',
179         command='$cxx $ldflags -o $out $in $libs',
180         description='LINK $out')
181 n.newline()
182
183 objs = []
184
185 if platform not in ('mingw', 'windows'):
186     n.comment('browse_py.h is used to inline browse.py.')
187     n.rule('inline',
188            command='src/inline.sh $varname < $in > $out',
189            description='INLINE $out')
190     n.build(built('browse_py.h'), 'inline', src('browse.py'),
191             implicit='src/inline.sh',
192             variables=[('varname', 'kBrowsePy')])
193     n.newline()
194
195     objs += cxx('browse', order_only=built('browse_py.h'))
196     n.newline()
197
198 n.comment('the depfile parser and ninja lexers are generated using re2c.')
199 n.rule('re2c',
200        command='re2c -b -i --no-generation-date -o $out $in',
201        description='RE2C $out')
202 # Generate the .cc files in the source directory so we can check them in.
203 n.build(src('depfile_parser.cc'), 're2c', src('depfile_parser.in.cc'))
204 n.build(src('lexer.cc'), 're2c', src('lexer.in.cc'))
205 n.newline()
206
207 n.comment('Core source files all build into ninja library.')
208 for name in ['build',
209              'build_log',
210              'clean',
211              'depfile_parser',
212              'disk_interface',
213              'edit_distance',
214              'eval_env',
215              'graph',
216              'graphviz',
217              'lexer',
218              'metrics',
219              'parsers',
220              'state',
221              'util']:
222     objs += cxx(name)
223 if platform == 'mingw' or platform == 'windows':
224     objs += cxx('subprocess-win32')
225     objs += cc('getopt')
226 else:
227     objs += cxx('subprocess')
228 if platform == 'windows':
229     ninja_lib = n.build(built('ninja.lib'), 'ar', objs)
230 else:
231     ninja_lib = n.build(built('libninja.a'), 'ar', objs)
232 n.newline()
233
234 if platform == 'windows':
235     libs.append('ninja.lib')
236 else:
237     libs.append('-lninja')
238
239 all_targets = []
240
241 n.comment('Main executable is library plus main() function.')
242 objs = cxx('ninja')
243 ninja = n.build(binary('ninja'), 'link', objs, implicit=ninja_lib,
244                 variables=[('libs', libs)])
245 n.newline()
246 all_targets += ninja
247
248 n.comment('Tests all build into ninja_test executable.')
249
250 variables = []
251 test_cflags = None
252 test_ldflags = None
253 test_libs = libs
254 objs = []
255 if options.with_gtest:
256     path = options.with_gtest
257
258     gtest_all_incs = '-I%s -I%s' % (path, os.path.join(path, 'include'))
259     gtest_cflags = '-fvisibility=hidden ' + gtest_all_incs
260     objs += n.build(built('gtest-all.o'), 'cxx',
261                     os.path.join(path, 'src/gtest-all.cc'),
262                     variables=[('cflags', gtest_cflags)])
263     objs += n.build(built('gtest_main.o'), 'cxx',
264                     os.path.join(path, 'src/gtest_main.cc'),
265                     variables=[('cflags', gtest_cflags)])
266
267     test_cflags = cflags + ['-I%s' % os.path.join(path, 'include')]
268 elif platform == 'windows':
269     test_libs.extend(['gtest_main.lib', 'gtest.lib'])
270 else:
271     test_libs.extend(['-lgtest_main', '-lgtest'])
272
273 for name in ['build_log_test',
274              'build_test',
275              'clean_test',
276              'depfile_parser_test',
277              'disk_interface_test',
278              'edit_distance_test',
279              'graph_test',
280              'lexer_test',
281              'parsers_test',
282              'state_test',
283              'subprocess_test',
284              'test',
285              'util_test']:
286     objs += cxx(name, variables=[('cflags', test_cflags)])
287
288 if platform != 'mingw' and platform != 'windows':
289     test_libs.append('-lpthread')
290 ninja_test = n.build(binary('ninja_test'), 'link', objs, implicit=ninja_lib,
291                      variables=[('ldflags', test_ldflags),
292                                 ('libs', test_libs)])
293 n.newline()
294 all_targets += ninja_test
295
296 n.comment('Perftest executable.')
297 objs = cxx('parser_perftest')
298 parser_perftest = n.build(binary('parser_perftest'), 'link', objs,
299                           implicit=ninja_lib,
300                           variables=[('libs', '-L$builddir -lninja')])
301 n.newline()
302 all_targets += parser_perftest
303
304 n.comment('Generate a graph using the "graph" tool.')
305 n.rule('gendot',
306        command='./ninja -t graph > $out')
307 n.rule('gengraph',
308        command='dot -Tpng $in > $out')
309 dot = n.build(built('graph.dot'), 'gendot', ['ninja', 'build.ninja'])
310 n.build('graph.png', 'gengraph', dot)
311 n.newline()
312
313 n.comment('Generate the manual using asciidoc.')
314 n.rule('asciidoc',
315        command='asciidoc -a toc -o $out $in',
316        description='ASCIIDOC $in')
317 manual = n.build(doc('manual.html'), 'asciidoc', doc('manual.asciidoc'))
318 n.build('manual', 'phony',
319         order_only=manual)
320 n.newline()
321
322 n.comment('Generate Doxygen.')
323 n.rule('doxygen',
324        command='doxygen $in',
325        description='DOXYGEN $in')
326 n.variable('doxygen_mainpage_generator',
327            src('gen_doxygen_mainpage.sh'))
328 n.rule('doxygen_mainpage',
329        command='$doxygen_mainpage_generator $in > $out',
330        description='DOXYGEN_MAINPAGE $out')
331 mainpage = n.build(built('doxygen_mainpage'), 'doxygen_mainpage',
332                    ['README', 'HACKING', 'COPYING'],
333                    implicit=['$doxygen_mainpage_generator'])
334 n.build('doxygen', 'doxygen', doc('doxygen.config'),
335         implicit=mainpage)
336 n.newline()
337
338 if host != 'mingw':
339     n.comment('Regenerate build files if build script changes.')
340     n.rule('configure',
341            command=options.with_python + ' configure.py $configure_args',
342            generator=True)
343     n.build('build.ninja', 'configure',
344             implicit=['configure.py', 'misc/ninja_syntax.py'])
345     n.newline()
346
347 n.comment('Build only the main binary by default.')
348 n.default(ninja)
349 n.newline()
350
351 n.build('all', 'phony', all_targets)
352
353 print 'wrote %s.' % BUILD_FILENAME