3 # Copyright 2001 Google Inc. All Rights Reserved.
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
9 # http://www.apache.org/licenses/LICENSE-2.0
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.
17 """Script that generates the build.ninja for ninja itself.
19 Projects that use ninja themselves should either write a similar script
20 or use a meta-build system that supports Ninja output."""
22 from __future__ import print_function
24 from optparse import OptionParser
27 import platform_helper
28 sys.path.insert(0, 'misc')
32 parser = OptionParser()
33 profilers = ['gmon', 'pprof']
34 parser.add_option('--platform',
35 help='target platform (' + '/'.join(platform_helper.platforms()) + ')',
36 choices=platform_helper.platforms())
37 parser.add_option('--host',
38 help='host platform (' + '/'.join(platform_helper.platforms()) + ')',
39 choices=platform_helper.platforms())
40 parser.add_option('--debug', action='store_true',
41 help='enable debugging extras',)
42 parser.add_option('--profile', metavar='TYPE',
44 help='enable profiling (' + '/'.join(profilers) + ')',)
45 parser.add_option('--with-gtest', metavar='PATH',
46 help='use gtest unpacked in directory PATH')
47 parser.add_option('--with-python', metavar='EXE',
48 help='use EXE as the Python interpreter',
49 default=os.path.basename(sys.executable))
50 (options, args) = parser.parse_args()
52 print('ERROR: extra unparsed command-line arguments:', args)
55 platform = platform_helper.Platform(options.platform)
57 host = platform_helper.Platform(options.host)
61 BUILD_FILENAME = 'build.ninja'
62 buildfile = open(BUILD_FILENAME, 'w')
63 n = ninja_syntax.Writer(buildfile)
64 n.comment('This file is used to build ninja itself.')
65 n.comment('It is generated by ' + os.path.basename(__file__) + '.')
68 n.variable('ninja_required_version', '1.3')
71 n.comment('The arguments passed to configure.py, for rerunning it.')
72 n.variable('configure_args', ' '.join(sys.argv[1:]))
73 env_keys = set(['CXX', 'AR', 'CFLAGS', 'LDFLAGS'])
74 configure_env = dict((k, os.environ[k]) for k in os.environ if k in env_keys)
76 config_str = ' '.join([k + '=' + configure_env[k] for k in configure_env])
77 n.variable('configure_env', config_str + '$ ')
80 CXX = configure_env.get('CXX', 'g++')
82 if platform.is_msvc():
87 return os.path.join('src', filename)
89 return os.path.join('$builddir', filename)
91 return os.path.join('doc', filename)
92 def cc(name, **kwargs):
93 return n.build(built(name + objext), 'cxx', src(name + '.c'), **kwargs)
94 def cxx(name, **kwargs):
95 return n.build(built(name + objext), 'cxx', src(name + '.cc'), **kwargs)
97 if platform.is_windows():
99 n.build(name, 'phony', exe)
103 n.variable('builddir', 'build')
104 n.variable('cxx', CXX)
105 if platform.is_msvc():
106 n.variable('ar', 'link')
108 n.variable('ar', configure_env.get('AR', 'ar'))
110 if platform.is_msvc():
111 cflags = ['/nologo', # Don't print startup banner.
112 '/Zi', # Create pdb with debug info.
113 '/W4', # Highest warning level.
114 '/WX', # Warnings as errors.
115 '/wd4530', '/wd4100', '/wd4706',
116 '/wd4512', '/wd4800', '/wd4702', '/wd4819',
117 # Disable warnings about passing "this" during initialization.
119 '/GR-', # Disable RTTI.
120 # Disable size_t -> int truncation warning.
121 # We never have strings or arrays larger than 2**31.
123 '/DNOMINMAX', '/D_CRT_SECURE_NO_WARNINGS',
124 '/D_VARIADIC_MAX=10',
125 '/DNINJA_PYTHON="%s"' % options.with_python]
126 ldflags = ['/DEBUG', '/libpath:$builddir']
127 if not options.debug:
128 cflags += ['/Ox', '/DNDEBUG', '/GL']
129 ldflags += ['/LTCG', '/OPT:REF', '/OPT:ICF']
131 cflags = ['-g', '-Wall', '-Wextra',
133 '-Wno-unused-parameter',
136 '-fvisibility=hidden', '-pipe',
137 '-Wno-missing-field-initializers',
138 '-DNINJA_PYTHON="%s"' % options.with_python]
140 cflags += ['-D_GLIBCXX_DEBUG', '-D_GLIBCXX_DEBUG_PEDANTIC']
141 cflags.remove('-fno-rtti') # Needed for above pedanticness.
143 cflags += ['-O2', '-DNDEBUG']
144 if 'clang' in os.path.basename(CXX):
145 cflags += ['-fcolor-diagnostics']
146 if platform.is_mingw():
147 cflags += ['-D_WIN32_WINNT=0x0501']
148 ldflags = ['-L$builddir']
151 if platform.is_mingw():
152 cflags.remove('-fvisibility=hidden');
153 ldflags.append('-static')
154 elif platform.is_sunos5():
155 cflags.remove('-fvisibility=hidden')
156 elif platform.is_msvc():
159 if options.profile == 'gmon':
161 ldflags.append('-pg')
162 elif options.profile == 'pprof':
163 cflags.append('-fno-omit-frame-pointer')
164 libs.extend(['-Wl,--no-as-needed', '-lprofiler'])
166 def shell_escape(str):
167 """Escape str such that it's interpreted as a single argument by
170 # This isn't complete, but it's just enough to make NINJA_PYTHON work.
171 if platform.is_windows():
174 return "'%s'" % str.replace("'", "\\'")
177 if 'CFLAGS' in configure_env:
178 cflags.append(configure_env['CFLAGS'])
179 n.variable('cflags', ' '.join(shell_escape(flag) for flag in cflags))
180 if 'LDFLAGS' in configure_env:
181 ldflags.append(configure_env['LDFLAGS'])
182 n.variable('ldflags', ' '.join(shell_escape(flag) for flag in ldflags))
185 if platform.is_msvc():
187 command='$cxx /showIncludes $cflags -c $in /Fo$out',
188 description='CXX $out',
192 command='$cxx -MMD -MT $out -MF $out.d $cflags -c $in -o $out',
195 description='CXX $out')
200 command='lib /nologo /ltcg /out:$out $in',
201 description='LIB $out')
202 elif host.is_mingw():
204 command='cmd /c $ar cqs $out.tmp $in && move /Y $out.tmp $out',
205 description='AR $out')
208 command='rm -f $out && $ar crs $out $in',
209 description='AR $out')
212 if platform.is_msvc():
214 command='$cxx $in $libs /nologo /link $ldflags /out:$out',
215 description='LINK $out')
218 command='$cxx $ldflags -o $out $in $libs',
219 description='LINK $out')
224 if not platform.is_windows() and not platform.is_solaris():
225 n.comment('browse_py.h is used to inline browse.py.')
227 command='src/inline.sh $varname < $in > $out',
228 description='INLINE $out')
229 n.build(built('browse_py.h'), 'inline', src('browse.py'),
230 implicit='src/inline.sh',
231 variables=[('varname', 'kBrowsePy')])
234 objs += cxx('browse', order_only=built('browse_py.h'))
237 n.comment('the depfile parser and ninja lexers are generated using re2c.')
241 proc = subprocess.Popen(['re2c', '-V'], stdout=subprocess.PIPE)
242 return int(proc.communicate()[0], 10) >= 1103
247 command='re2c -b -i --no-generation-date -o $out $in',
248 description='RE2C $out')
249 # Generate the .cc files in the source directory so we can check them in.
250 n.build(src('depfile_parser.cc'), 're2c', src('depfile_parser.in.cc'))
251 n.build(src('lexer.cc'), 're2c', src('lexer.in.cc'))
253 print("warning: A compatible version of re2c (>= 0.11.3) was not found; "
254 "changes to src/*.in.cc will not affect your build.")
257 n.comment('Core source files all build into ninja library.')
258 for name in ['build',
277 if platform.is_windows():
278 for name in ['subprocess-win32',
279 'includes_normalize-win32',
281 'msvc_helper_main-win32']:
283 if platform.is_msvc():
284 objs += cxx('minidump-win32')
287 objs += cxx('subprocess-posix')
288 if platform.is_msvc():
289 ninja_lib = n.build(built('ninja.lib'), 'ar', objs)
291 ninja_lib = n.build(built('libninja.a'), 'ar', objs)
294 if platform.is_msvc():
295 libs.append('ninja.lib')
297 libs.append('-lninja')
301 n.comment('Main executable is library plus main() function.')
303 ninja = n.build(binary('ninja'), 'link', objs, implicit=ninja_lib,
304 variables=[('libs', libs)])
308 n.comment('Tests all build into ninja_test executable.')
311 test_cflags = cflags + ['-DGTEST_HAS_RTTI=0']
315 if options.with_gtest:
316 path = options.with_gtest
318 gtest_all_incs = '-I%s -I%s' % (path, os.path.join(path, 'include'))
319 if platform.is_msvc():
320 gtest_cflags = '/nologo /EHsc /Zi /D_VARIADIC_MAX=10 ' + gtest_all_incs
322 gtest_cflags = '-fvisibility=hidden ' + gtest_all_incs
323 objs += n.build(built('gtest-all' + objext), 'cxx',
324 os.path.join(path, 'src', 'gtest-all.cc'),
325 variables=[('cflags', gtest_cflags)])
327 test_cflags.append('-I%s' % os.path.join(path, 'include'))
329 # Use gtest from system.
330 if platform.is_msvc():
331 test_libs.extend(['gtest_main.lib', 'gtest.lib'])
333 test_libs.extend(['-lgtest_main', '-lgtest'])
335 n.variable('test_cflags', test_cflags)
336 for name in ['build_log_test',
339 'depfile_parser_test',
341 'disk_interface_test',
342 'edit_distance_test',
345 'manifest_parser_test',
351 objs += cxx(name, variables=[('cflags', '$test_cflags')])
352 if platform.is_windows():
353 for name in ['includes_normalize_test', 'msvc_helper_test']:
354 objs += cxx(name, variables=[('cflags', test_cflags)])
356 if not platform.is_windows():
357 test_libs.append('-lpthread')
358 ninja_test = n.build(binary('ninja_test'), 'link', objs, implicit=ninja_lib,
359 variables=[('ldflags', test_ldflags),
360 ('libs', test_libs)])
362 all_targets += ninja_test
365 n.comment('Ancillary executables.')
366 objs = cxx('parser_perftest')
367 all_targets += n.build(binary('parser_perftest'), 'link', objs,
368 implicit=ninja_lib, variables=[('libs', libs)])
369 objs = cxx('build_log_perftest')
370 all_targets += n.build(binary('build_log_perftest'), 'link', objs,
371 implicit=ninja_lib, variables=[('libs', libs)])
372 objs = cxx('canon_perftest')
373 all_targets += n.build(binary('canon_perftest'), 'link', objs,
374 implicit=ninja_lib, variables=[('libs', libs)])
375 objs = cxx('hash_collision_bench')
376 all_targets += n.build(binary('hash_collision_bench'), 'link', objs,
377 implicit=ninja_lib, variables=[('libs', libs)])
380 n.comment('Generate a graph using the "graph" tool.')
382 command='./ninja -t graph all > $out')
384 command='dot -Tpng $in > $out')
385 dot = n.build(built('graph.dot'), 'gendot', ['ninja', 'build.ninja'])
386 n.build('graph.png', 'gengraph', dot)
389 n.comment('Generate the manual using asciidoc.')
391 command='asciidoc -b docbook -d book -o $out $in',
392 description='ASCIIDOC $out')
394 command='xsltproc --nonet doc/docbook.xsl $in > $out',
395 description='XSLTPROC $out')
396 xml = n.build(built('manual.xml'), 'asciidoc', doc('manual.asciidoc'))
397 manual = n.build(doc('manual.html'), 'xsltproc', xml,
398 implicit=doc('style.css'))
399 n.build('manual', 'phony',
403 n.comment('Generate Doxygen.')
405 command='doxygen $in',
406 description='DOXYGEN $in')
407 n.variable('doxygen_mainpage_generator',
408 src('gen_doxygen_mainpage.sh'))
409 n.rule('doxygen_mainpage',
410 command='$doxygen_mainpage_generator $in > $out',
411 description='DOXYGEN_MAINPAGE $out')
412 mainpage = n.build(built('doxygen_mainpage'), 'doxygen_mainpage',
413 ['README', 'COPYING'],
414 implicit=['$doxygen_mainpage_generator'])
415 n.build('doxygen', 'doxygen', doc('doxygen.config'),
419 if not host.is_mingw():
420 n.comment('Regenerate build files if build script changes.')
422 command='${configure_env}%s configure.py $configure_args' %
425 n.build('build.ninja', 'configure',
426 implicit=['configure.py', os.path.normpath('misc/ninja_syntax.py')])
433 n.comment('Packaging')
435 command="misc/packaging/rpmbuild.sh",
436 description='Building rpms..')
437 n.build('rpm', 'rpmbuild')
440 n.build('all', 'phony', all_targets)
442 print('wrote %s.' % BUILD_FILENAME)