source: extensions/gsdl-video/trunk/installed/cmdline/lib/ruby/1.8/mkmf.rb@ 18425

Last change on this file since 18425 was 18425, checked in by davidb, 15 years ago

Video extension to Greenstone

File size: 42.1 KB
Line 
1# module to create Makefile for extension modules
2# invoke like: ruby -r mkmf extconf.rb
3
4require 'rbconfig'
5require 'fileutils'
6require 'shellwords'
7
8CONFIG = Config::MAKEFILE_CONFIG
9ORIG_LIBPATH = ENV['LIB']
10
11CXX_EXT = %w[cc cxx cpp]
12if /mswin|bccwin|mingw|msdosdjgpp|human|os2/ !~ CONFIG['build_os']
13 CXX_EXT.concat(%w[C])
14end
15SRC_EXT = %w[c m] << CXX_EXT
16$static = $config_h = nil
17$default_static = $static
18
19unless defined? $configure_args
20 $configure_args = {}
21 args = CONFIG["configure_args"]
22 if ENV["CONFIGURE_ARGS"]
23 args << " " << ENV["CONFIGURE_ARGS"]
24 end
25 for arg in Shellwords::shellwords(args)
26 arg, val = arg.split('=', 2)
27 next unless arg
28 arg.tr!('_', '-')
29 if arg.sub!(/^(?!--)/, '--')
30 val or next
31 arg.downcase!
32 end
33 next if /^--(?:top|topsrc|src|cur)dir$/ =~ arg
34 $configure_args[arg] = val || true
35 end
36 for arg in ARGV
37 arg, val = arg.split('=', 2)
38 next unless arg
39 arg.tr!('_', '-')
40 if arg.sub!(/^(?!--)/, '--')
41 val or next
42 arg.downcase!
43 end
44 $configure_args[arg] = val || true
45 end
46end
47
48$libdir = CONFIG["libdir"]
49$rubylibdir = CONFIG["rubylibdir"]
50$archdir = CONFIG["archdir"]
51$sitedir = CONFIG["sitedir"]
52$sitelibdir = CONFIG["sitelibdir"]
53$sitearchdir = CONFIG["sitearchdir"]
54
55$mswin = /mswin/ =~ RUBY_PLATFORM
56$bccwin = /bccwin/ =~ RUBY_PLATFORM
57$mingw = /mingw/ =~ RUBY_PLATFORM
58$cygwin = /cygwin/ =~ RUBY_PLATFORM
59$human = /human/ =~ RUBY_PLATFORM
60$netbsd = /netbsd/ =~ RUBY_PLATFORM
61$os2 = /os2/ =~ RUBY_PLATFORM
62$beos = /beos/ =~ RUBY_PLATFORM
63$solaris = /solaris/ =~ RUBY_PLATFORM
64$dest_prefix_pattern = (File::PATH_SEPARATOR == ';' ? /\A([[:alpha:]]:)?/ : /\A/)
65
66def config_string(key, config = CONFIG)
67 s = config[key] and !s.empty? and block_given? ? yield(s) : s
68end
69
70def dir_re(dir)
71 Regexp.new('\$(?:\('+dir+'\)|\{'+dir+'\})(?:\$(?:\(target_prefix\)|\{target_prefix\}))?')
72end
73
74INSTALL_DIRS = [
75 [dir_re('commondir'), "$(RUBYCOMMONDIR)"],
76 [dir_re("sitedir"), "$(RUBYCOMMONDIR)"],
77 [dir_re('rubylibdir'), "$(RUBYLIBDIR)"],
78 [dir_re('archdir'), "$(RUBYARCHDIR)"],
79 [dir_re('sitelibdir'), "$(RUBYLIBDIR)"],
80 [dir_re('sitearchdir'), "$(RUBYARCHDIR)"]
81]
82
83def install_dirs(target_prefix = nil)
84 if $extout
85 dirs = [
86 ['RUBYCOMMONDIR', '$(extout)/common'],
87 ['RUBYLIBDIR', '$(RUBYCOMMONDIR)$(target_prefix)'],
88 ['RUBYARCHDIR', '$(extout)/$(arch)$(target_prefix)'],
89 ['extout', "#$extout"],
90 ['extout_prefix', "#$extout_prefix"],
91 ]
92 elsif $extmk
93 dirs = [
94 ['RUBYCOMMONDIR', '$(rubylibdir)'],
95 ['RUBYLIBDIR', '$(rubylibdir)$(target_prefix)'],
96 ['RUBYARCHDIR', '$(archdir)$(target_prefix)'],
97 ]
98 else
99 dirs = [
100 ['RUBYCOMMONDIR', '$(sitedir)$(target_prefix)'],
101 ['RUBYLIBDIR', '$(sitelibdir)$(target_prefix)'],
102 ['RUBYARCHDIR', '$(sitearchdir)$(target_prefix)'],
103 ]
104 end
105 dirs << ['target_prefix', (target_prefix ? "/#{target_prefix}" : "")]
106 dirs
107end
108
109def map_dir(dir, map = nil)
110 map ||= INSTALL_DIRS
111 map.inject(dir) {|dir, (orig, new)| dir.gsub(orig, new)}
112end
113
114topdir = File.dirname(libdir = File.dirname(__FILE__))
115extdir = File.expand_path("ext", topdir)
116$extmk = File.expand_path($0)[0, extdir.size+1] == extdir+"/"
117if not $extmk and File.exist?(Config::CONFIG["archdir"] + "/ruby.h")
118 $hdrdir = $topdir = Config::CONFIG["archdir"]
119elsif File.exist?(($top_srcdir ||= topdir) + "/ruby.h") and
120 File.exist?(($topdir ||= Config::CONFIG["topdir"]) + "/config.h")
121 $hdrdir = $top_srcdir
122else
123 abort "can't find header files for ruby."
124end
125
126OUTFLAG = CONFIG['OUTFLAG']
127CPPOUTFILE = CONFIG['CPPOUTFILE']
128
129CONFTEST_C = "conftest.c"
130
131class String
132 def quote
133 /\s/ =~ self ? "\"#{self}\"" : self
134 end
135end
136class Array
137 def quote
138 map {|s| s.quote}
139 end
140end
141
142def rm_f(*files)
143 FileUtils.rm_f(Dir[files.join("\0")])
144end
145
146def modified?(target, times)
147 (t = File.mtime(target)) rescue return nil
148 Array === times or times = [times]
149 t if times.all? {|n| n <= t}
150end
151
152def merge_libs(*libs)
153 libs.inject([]) do |x, y|
154 xy = x & y
155 xn = yn = 0
156 y = y.inject([]) {|ary, e| ary.last == e ? ary : ary << e}
157 y.each_with_index do |v, yi|
158 if xy.include?(v)
159 xi = [x.index(v), xn].max()
160 x[xi, 1] = y[yn..yi]
161 xn, yn = xi + (yi - yn + 1), yi + 1
162 end
163 end
164 x.concat(y[yn..-1] || [])
165 end
166end
167
168module Logging
169 @log = nil
170 @logfile = 'mkmf.log'
171 @orgerr = $stderr.dup
172 @orgout = $stdout.dup
173 @postpone = 0
174
175 def self::open
176 @log ||= File::open(@logfile, 'w')
177 @log.sync = true
178 $stderr.reopen(@log)
179 $stdout.reopen(@log)
180 yield
181 ensure
182 $stderr.reopen(@orgerr)
183 $stdout.reopen(@orgout)
184 end
185
186 def self::message(*s)
187 @log ||= File::open(@logfile, 'w')
188 @log.sync = true
189 @log.printf(*s)
190 end
191
192 def self::logfile file
193 @logfile = file
194 if @log and not @log.closed?
195 @log.flush
196 @log.close
197 @log = nil
198 end
199 end
200
201 def self::postpone
202 tmplog = "mkmftmp#{@postpone += 1}.log"
203 open do
204 log, *save = @log, @logfile, @orgout, @orgerr
205 @log, @logfile, @orgout, @orgerr = nil, tmplog, log, log
206 begin
207 log.print(open {yield})
208 @log.close
209 File::open(tmplog) {|t| FileUtils.copy_stream(t, log)}
210 ensure
211 @log, @logfile, @orgout, @orgerr = log, *save
212 @postpone -= 1
213 rm_f tmplog
214 end
215 end
216 end
217end
218
219def xsystem command
220 Logging::open do
221 puts command.quote
222 system(command)
223 end
224end
225
226def xpopen command, *mode, &block
227 Logging::open do
228 case mode[0]
229 when nil, /^r/
230 puts "#{command} |"
231 else
232 puts "| #{command}"
233 end
234 IO.popen(command, *mode, &block)
235 end
236end
237
238def log_src(src)
239 src = src.split(/^/)
240 fmt = "%#{src.size.to_s.size}d: %s"
241 Logging::message <<"EOM"
242checked program was:
243/* begin */
244EOM
245 src.each_with_index {|line, no| Logging::message fmt, no+1, line}
246 Logging::message <<"EOM"
247/* end */
248
249EOM
250end
251
252def create_tmpsrc(src)
253 src = yield(src) if block_given?
254 src = src.gsub(/[ \t]+$/, '').gsub(/\A\n+|^\n+$/, '').sub(/[^\n]\z/, "\\&\n")
255 open(CONFTEST_C, "wb") do |cfile|
256 cfile.print src
257 end
258 src
259end
260
261def try_do(src, command, &b)
262 src = create_tmpsrc(src, &b)
263 xsystem(command)
264ensure
265 log_src(src)
266end
267
268def link_command(ldflags, opt="", libpath=$DEFLIBPATH|$LIBPATH)
269 Config::expand(TRY_LINK.dup,
270 CONFIG.merge('hdrdir' => $hdrdir.quote,
271 'src' => CONFTEST_C,
272 'INCFLAGS' => $INCFLAGS,
273 'CPPFLAGS' => $CPPFLAGS,
274 'CFLAGS' => "#$CFLAGS",
275 'ARCH_FLAG' => "#$ARCH_FLAG",
276 'LDFLAGS' => "#$LDFLAGS #{ldflags}",
277 'LIBPATH' => libpathflag(libpath),
278 'LOCAL_LIBS' => "#$LOCAL_LIBS #$libs",
279 'LIBS' => "#$LIBRUBYARG_STATIC #{opt} #$LIBS"))
280end
281
282def cc_command(opt="")
283 Config::expand("$(CC) #$INCFLAGS #$CPPFLAGS #$CFLAGS #$ARCH_FLAG #{opt} -c #{CONFTEST_C}",
284 CONFIG.merge('hdrdir' => $hdrdir.quote, 'srcdir' => $srcdir.quote))
285end
286
287def cpp_command(outfile, opt="")
288 Config::expand("$(CPP) #$INCFLAGS #$CPPFLAGS #$CFLAGS #{opt} #{CONFTEST_C} #{outfile}",
289 CONFIG.merge('hdrdir' => $hdrdir.quote, 'srcdir' => $srcdir.quote))
290end
291
292def libpathflag(libpath=$DEFLIBPATH|$LIBPATH)
293 libpath.map{|x|
294 (x == "$(topdir)" ? LIBPATHFLAG : LIBPATHFLAG+RPATHFLAG) % x.quote
295 }.join
296end
297
298def try_link0(src, opt="", &b)
299 try_do(src, link_command("", opt), &b)
300end
301
302def try_link(src, opt="", &b)
303 try_link0(src, opt, &b)
304ensure
305 rm_f "conftest*", "c0x32*"
306end
307
308def try_compile(src, opt="", &b)
309 try_do(src, cc_command(opt), &b)
310ensure
311 rm_f "conftest*"
312end
313
314def try_cpp(src, opt="", &b)
315 try_do(src, cpp_command(CPPOUTFILE, opt), &b)
316ensure
317 rm_f "conftest*"
318end
319
320def cpp_include(header)
321 if header
322 header = [header] unless header.kind_of? Array
323 header.map {|h| "#include <#{h}>\n"}.join
324 else
325 ""
326 end
327end
328
329def with_cppflags(flags)
330 cppflags = $CPPFLAGS
331 $CPPFLAGS = flags
332 ret = yield
333ensure
334 $CPPFLAGS = cppflags unless ret
335end
336
337def with_cflags(flags)
338 cflags = $CFLAGS
339 $CFLAGS = flags
340 ret = yield
341ensure
342 $CFLAGS = cflags unless ret
343end
344
345def with_ldflags(flags)
346 ldflags = $LDFLAGS
347 $LDFLAGS = flags
348 ret = yield
349ensure
350 $LDFLAGS = ldflags unless ret
351end
352
353def try_static_assert(expr, headers = nil, opt = "", &b)
354 headers = cpp_include(headers)
355 try_compile(<<SRC, opt, &b)
356#{COMMON_HEADERS}
357#{headers}
358/*top*/
359int conftest_const[(#{expr}) ? 1 : -1];
360SRC
361end
362
363def try_constant(const, headers = nil, opt = "", &b)
364 includes = cpp_include(headers)
365 if CROSS_COMPILING
366 if try_static_assert("#{const} > 0", headers, opt)
367 # positive constant
368 elsif try_static_assert("#{const} < 0", headers, opt)
369 neg = true
370 const = "-(#{const})"
371 elsif try_static_assert("#{const} == 0", headers, opt)
372 return 0
373 else
374 # not a constant
375 return nil
376 end
377 upper = 1
378 lower = 0
379 until try_static_assert("#{const} <= #{upper}", headers, opt)
380 lower = upper
381 upper <<= 1
382 end
383 return nil unless lower
384 while upper > lower + 1
385 mid = (upper + lower) / 2
386 if try_static_assert("#{const} > #{mid}", headers, opt)
387 lower = mid
388 else
389 upper = mid
390 end
391 end
392 upper = -upper if neg
393 return upper
394 else
395 src = %{#{COMMON_HEADERS}
396#{includes}
397#include <stdio.h>
398/*top*/
399int conftest_const = (int)(#{const});
400int main() {printf("%d\\n", conftest_const); return 0;}
401}
402 if try_link0(src, opt, &b)
403 xpopen("./conftest") do |f|
404 return Integer(f.gets)
405 end
406 end
407 end
408 nil
409end
410
411def try_func(func, libs, headers = nil, &b)
412 headers = cpp_include(headers)
413 try_link(<<"SRC", libs, &b) or try_link(<<"SRC", libs, &b)
414#{COMMON_HEADERS}
415#{headers}
416/*top*/
417int main() { return 0; }
418int t() { void ((*volatile p)()); p = (void ((*)()))#{func}; return 0; }
419SRC
420#{headers}
421/*top*/
422int main() { return 0; }
423int t() { #{func}(); return 0; }
424SRC
425end
426
427def try_var(var, headers = nil, &b)
428 headers = cpp_include(headers)
429 try_compile(<<"SRC", &b)
430#{COMMON_HEADERS}
431#{headers}
432/*top*/
433int main() { return 0; }
434int t() { const volatile void *volatile p; p = (void *)&#{var}; return 0; }
435SRC
436end
437
438def egrep_cpp(pat, src, opt = "", &b)
439 src = create_tmpsrc(src, &b)
440 xpopen(cpp_command('', opt)) do |f|
441 if Regexp === pat
442 puts(" ruby -ne 'print if #{pat.inspect}'")
443 f.grep(pat) {|l|
444 puts "#{f.lineno}: #{l}"
445 return true
446 }
447 false
448 else
449 puts(" egrep '#{pat}'")
450 begin
451 stdin = $stdin.dup
452 $stdin.reopen(f)
453 system("egrep", pat)
454 ensure
455 $stdin.reopen(stdin)
456 end
457 end
458 end
459ensure
460 rm_f "conftest*"
461 log_src(src)
462end
463
464def macro_defined?(macro, src, opt = "", &b)
465 src = src.sub(/[^\n]\z/, "\\&\n")
466 try_compile(src + <<"SRC", opt, &b)
467/*top*/
468#ifndef #{macro}
469# error
470>>>>>> #{macro} undefined <<<<<<
471#endif
472SRC
473end
474
475def try_run(src, opt = "", &b)
476 if try_link0(src, opt, &b)
477 xsystem("./conftest")
478 else
479 nil
480 end
481ensure
482 rm_f "conftest*"
483end
484
485def install_files(mfile, ifiles, map = nil, srcprefix = nil)
486 ifiles or return
487 srcprefix ||= '$(srcdir)'
488 Config::expand(srcdir = srcprefix.dup)
489 dirs = []
490 path = Hash.new {|h, i| h[i] = dirs.push([i])[-1]}
491 ifiles.each do |files, dir, prefix|
492 dir = map_dir(dir, map)
493 prefix = %r|\A#{Regexp.quote(prefix)}/?| if prefix
494 if /\A\.\// =~ files
495 # install files which are in current working directory.
496 files = files[2..-1]
497 len = nil
498 else
499 # install files which are under the $(srcdir).
500 files = File.join(srcdir, files)
501 len = srcdir.size
502 end
503 f = nil
504 Dir.glob(files) do |f|
505 f[0..len] = "" if len
506 d = File.dirname(f)
507 d.sub!(prefix, "") if prefix
508 d = (d.empty? || d == ".") ? dir : File.join(dir, d)
509 f = File.join(srcprefix, f) if len
510 path[d] << f
511 end
512 unless len or f
513 d = File.dirname(files)
514 d.sub!(prefix, "") if prefix
515 d = (d.empty? || d == ".") ? dir : File.join(dir, d)
516 path[d] << files
517 end
518 end
519 dirs
520end
521
522def install_rb(mfile, dest, srcdir = nil)
523 install_files(mfile, [["lib/**/*.rb", dest, "lib"]], nil, srcdir)
524end
525
526def append_library(libs, lib)
527 format(LIBARG, lib) + " " + libs
528end
529
530def message(*s)
531 unless $extmk and not $VERBOSE
532 printf(*s)
533 $stdout.flush
534 end
535end
536
537def checking_for(m, fmt = nil)
538 f = caller[0][/in `(.*)'$/, 1] and f << ": " #` for vim
539 m = "checking #{/\Acheck/ =~ f ? '' : 'for '}#{m}... "
540 message "%s", m
541 a = r = nil
542 Logging::postpone do
543 r = yield
544 a = (fmt ? fmt % r : r ? "yes" : "no") << "\n"
545 "#{f}#{m}-------------------- #{a}\n"
546 end
547 message(a)
548 Logging::message "--------------------\n\n"
549 r
550end
551
552def checking_message(target, place = nil, opt = nil)
553 [["in", place], ["with", opt]].inject("#{target}") do |msg, (pre, noun)|
554 if noun
555 [[:to_str], [:join, ","], [:to_s]].each do |meth, *args|
556 if noun.respond_to?(meth)
557 break noun = noun.send(meth, *args)
558 end
559 end
560 msg << " #{pre} #{noun}" unless noun.empty?
561 end
562 msg
563 end
564end
565
566# Returns whether or not +macro+ is defined either in the common header
567# files or within any +headers+ you provide.
568#
569# Any options you pass to +opt+ are passed along to the compiler.
570#
571def have_macro(macro, headers = nil, opt = "", &b)
572 checking_for checking_message(macro, headers, opt) do
573 macro_defined?(macro, cpp_include(headers), opt, &b)
574 end
575end
576
577# Returns whether or not the given entry point +func+ can be found within
578# +lib+. If +func+ is nil, the 'main()' entry point is used by default.
579# If found, it adds the library to list of libraries to be used when linking
580# your extension.
581#
582# If +headers+ are provided, it will include those header files as the
583# header files it looks in when searching for +func+.
584#
585# Real name of the library to be linked can be altered by
586# '--with-FOOlib' configuration option.
587#
588def have_library(lib, func = nil, headers = nil, &b)
589 func = "main" if !func or func.empty?
590 lib = with_config(lib+'lib', lib)
591 checking_for checking_message("#{func}()", LIBARG%lib) do
592 if COMMON_LIBS.include?(lib)
593 true
594 else
595 libs = append_library($libs, lib)
596 if try_func(func, libs, headers, &b)
597 $libs = libs
598 true
599 else
600 false
601 end
602 end
603 end
604end
605
606# Returns whether or not the entry point +func+ can be found within the library
607# +lib+ in one of the +paths+ specified, where +paths+ is an array of strings.
608# If +func+ is nil , then the main() function is used as the entry point.
609#
610# If +lib+ is found, then the path it was found on is added to the list of
611# library paths searched and linked against.
612#
613def find_library(lib, func, *paths, &b)
614 func = "main" if !func or func.empty?
615 lib = with_config(lib+'lib', lib)
616 paths = paths.collect {|path| path.split(File::PATH_SEPARATOR)}.flatten
617 checking_for "#{func}() in #{LIBARG%lib}" do
618 libpath = $LIBPATH
619 libs = append_library($libs, lib)
620 begin
621 until r = try_func(func, libs, &b) or paths.empty?
622 $LIBPATH = libpath | [paths.shift]
623 end
624 if r
625 $libs = libs
626 libpath = nil
627 end
628 ensure
629 $LIBPATH = libpath if libpath
630 end
631 r
632 end
633end
634
635# Returns whether or not the function +func+ can be found in the common
636# header files, or within any +headers+ that you provide. If found, a
637# macro is passed as a preprocessor constant to the compiler using the
638# function name, in uppercase, prepended with 'HAVE_'.
639#
640# For example, if have_func('foo') returned true, then the HAVE_FOO
641# preprocessor macro would be passed to the compiler.
642#
643def have_func(func, headers = nil, &b)
644 checking_for checking_message("#{func}()", headers) do
645 if try_func(func, $libs, headers, &b)
646 $defs.push(format("-DHAVE_%s", func.upcase))
647 true
648 else
649 false
650 end
651 end
652end
653
654# Returns whether or not the variable +var+ can be found in the common
655# header files, or within any +headers+ that you provide. If found, a
656# macro is passed as a preprocessor constant to the compiler using the
657# variable name, in uppercase, prepended with 'HAVE_'.
658#
659# For example, if have_var('foo') returned true, then the HAVE_FOO
660# preprocessor macro would be passed to the compiler.
661#
662def have_var(var, headers = nil, &b)
663 checking_for checking_message(var, headers) do
664 if try_var(var, headers, &b)
665 $defs.push(format("-DHAVE_%s", var.upcase))
666 true
667 else
668 false
669 end
670 end
671end
672
673# Returns whether or not the given +header+ file can be found on your system.
674# If found, a macro is passed as a preprocessor constant to the compiler using
675# the header file name, in uppercase, prepended with 'HAVE_'.
676#
677# For example, if have_header('foo.h') returned true, then the HAVE_FOO_H
678# preprocessor macro would be passed to the compiler.
679#
680def have_header(header, &b)
681 checking_for header do
682 if try_cpp(cpp_include(header), &b)
683 $defs.push(format("-DHAVE_%s", header.tr("a-z./\055", "A-Z___")))
684 true
685 else
686 false
687 end
688 end
689end
690
691# Instructs mkmf to search for the given +header+ in any of the +paths+
692# provided, and returns whether or not it was found in those paths.
693#
694# If the header is found then the path it was found on is added to the list
695# of included directories that are sent to the compiler (via the -I switch).
696#
697def find_header(header, *paths)
698 header = cpp_include(header)
699 checking_for header do
700 if try_cpp(header)
701 true
702 else
703 found = false
704 paths.each do |dir|
705 opt = "-I#{dir}".quote
706 if try_cpp(header, opt)
707 $INCFLAGS << " " << opt
708 found = true
709 break
710 end
711 end
712 found
713 end
714 end
715end
716
717# Returns whether or not the struct of type +type+ contains +member+. If
718# it does not, or the struct type can't be found, then false is returned. You
719# may optionally specify additional +headers+ in which to look for the struct
720# (in addition to the common header files).
721#
722# If found, a macro is passed as a preprocessor constant to the compiler using
723# the member name, in uppercase, prepended with 'HAVE_ST_'.
724#
725# For example, if have_struct_member('foo', 'bar') returned true, then the
726# HAVE_ST_BAR preprocessor macro would be passed to the compiler.
727#
728def have_struct_member(type, member, headers = nil, &b)
729 checking_for checking_message("#{type}.#{member}", headers) do
730 if try_compile(<<"SRC", &b)
731#{COMMON_HEADERS}
732#{cpp_include(headers)}
733/*top*/
734int main() { return 0; }
735int s = (char *)&((#{type}*)0)->#{member} - (char *)0;
736SRC
737 $defs.push(format("-DHAVE_ST_%s", member.upcase))
738 true
739 else
740 false
741 end
742 end
743end
744
745# Returns whether or not the static type +type+ is defined. You may
746# optionally pass additional +headers+ to check against in addition to the
747# common header files.
748#
749# You may also pass additional flags to +opt+ which are then passed along to
750# the compiler.
751#
752# If found, a macro is passed as a preprocessor constant to the compiler using
753# the type name, in uppercase, prepended with 'HAVE_TYPE_'.
754#
755# For example, if have_type('foo') returned true, then the HAVE_TYPE_FOO
756# preprocessor macro would be passed to the compiler.
757#
758def have_type(type, headers = nil, opt = "", &b)
759 checking_for checking_message(type, headers, opt) do
760 headers = cpp_include(headers)
761 if try_compile(<<"SRC", opt, &b)
762#{COMMON_HEADERS}
763#{headers}
764/*top*/
765typedef #{type} conftest_type;
766static conftest_type conftestval[sizeof(conftest_type)?1:-1];
767SRC
768 $defs.push(format("-DHAVE_TYPE_%s", type.strip.upcase.tr_s("^A-Z0-9_", "_")))
769 true
770 else
771 false
772 end
773 end
774end
775
776# Returns the size of the given +type+. You may optionally specify additional
777# +headers+ to search in for the +type+.
778#
779# If found, a macro is passed as a preprocessor constant to the compiler using
780# the type name, in uppercase, prepended with 'SIZEOF_', followed by the type
781# name, followed by '=X' where 'X' is the actual size.
782#
783# For example, if check_sizeof('mystruct') returned 12, then the
784# SIZEOF_MYSTRUCT=12 preprocessor macro would be passed to the compiler.
785#
786def check_sizeof(type, headers = nil, &b)
787 expr = "sizeof(#{type})"
788 fmt = "%d"
789 def fmt.%(x)
790 x ? super : "failed"
791 end
792 checking_for checking_message("size of #{type}", headers), fmt do
793 if size = try_constant(expr, headers, &b)
794 $defs.push(format("-DSIZEOF_%s=%d", type.upcase.tr_s("^A-Z0-9_", "_"), size))
795 size
796 end
797 end
798end
799
800def scalar_ptr_type?(type, member = nil, headers = nil, &b)
801 try_compile(<<"SRC", &b) # pointer
802#{COMMON_HEADERS}
803#{cpp_include(headers)}
804/*top*/
805volatile #{type} conftestval;
806int main() { return 0; }
807int t() {return (int)(1-*(conftestval#{member ? ".#{member}" : ""}));}
808SRC
809end
810
811def scalar_type?(type, member = nil, headers = nil, &b)
812 try_compile(<<"SRC", &b) # pointer
813#{COMMON_HEADERS}
814#{cpp_include(headers)}
815/*top*/
816volatile #{type} conftestval;
817int main() { return 0; }
818int t() {return (int)(1-(conftestval#{member ? ".#{member}" : ""}));}
819SRC
820end
821
822def what_type?(type, member = nil, headers = nil, &b)
823 m = "#{type}"
824 name = type
825 if member
826 m << "." << member
827 name = "(((#{type} *)0)->#{member})"
828 end
829 fmt = "seems %s"
830 def fmt.%(x)
831 x ? super : "unknown"
832 end
833 checking_for checking_message(m, headers), fmt do
834 if scalar_ptr_type?(type, member, headers, &b)
835 if try_static_assert("sizeof(*#{name}) == 1", headers)
836 "string"
837 end
838 elsif scalar_type?(type, member, headers, &b)
839 if try_static_assert("sizeof(#{name}) > sizeof(long)", headers)
840 "long long"
841 elsif try_static_assert("sizeof(#{name}) > sizeof(int)", headers)
842 "long"
843 elsif try_static_assert("sizeof(#{name}) > sizeof(short)", headers)
844 "int"
845 elsif try_static_assert("sizeof(#{name}) > 1", headers)
846 "short"
847 else
848 "char"
849 end
850 end
851 end
852end
853
854def find_executable0(bin, path = nil)
855 ext = config_string('EXEEXT')
856 if File.expand_path(bin) == bin
857 return bin if File.executable?(bin)
858 ext and File.executable?(file = bin + ext) and return file
859 return nil
860 end
861 if path ||= ENV['PATH']
862 path = path.split(File::PATH_SEPARATOR)
863 else
864 path = %w[/usr/local/bin /usr/ucb /usr/bin /bin]
865 end
866 file = nil
867 path.each do |dir|
868 return file if File.executable?(file = File.join(dir, bin))
869 return file if ext and File.executable?(file << ext)
870 end
871 nil
872end
873
874def find_executable(bin, path = nil)
875 checking_for checking_message(bin, path) do
876 find_executable0(bin, path)
877 end
878end
879
880def arg_config(config, *defaults, &block)
881 $arg_config << [config, *defaults]
882 defaults << nil if !block and defaults.empty?
883 $configure_args.fetch(config.tr('_', '-'), *defaults, &block)
884end
885
886def with_config(config, *defaults)
887 config = config.sub(/^--with[-_]/, '')
888 val = arg_config("--with-"+config) do
889 if arg_config("--without-"+config)
890 false
891 elsif block_given?
892 yield(config, *defaults)
893 else
894 break *defaults
895 end
896 end
897 case val
898 when "yes"
899 true
900 when "no"
901 false
902 else
903 val
904 end
905end
906
907def enable_config(config, *defaults)
908 if arg_config("--enable-"+config)
909 true
910 elsif arg_config("--disable-"+config)
911 false
912 elsif block_given?
913 yield(config, *defaults)
914 else
915 return *defaults
916 end
917end
918
919def create_header(header = "extconf.h")
920 message "creating %s\n", header
921 sym = header.tr("a-z./\055", "A-Z___")
922 hdr = ["#ifndef #{sym}\n#define #{sym}\n"]
923 for line in $defs
924 case line
925 when /^-D([^=]+)(?:=(.*))?/
926 hdr << "#define #$1 #{$2 ? Shellwords.shellwords($2)[0] : 1}\n"
927 when /^-U(.*)/
928 hdr << "#undef #$1\n"
929 end
930 end
931 hdr << "#endif\n"
932 hdr = hdr.join
933 unless (IO.read(header) == hdr rescue false)
934 open(header, "w") do |hfile|
935 hfile.write(hdr)
936 end
937 end
938 $extconf_h = header
939end
940
941# Sets a +target+ name that the user can then use to configure various 'with'
942# options with on the command line by using that name. For example, if the
943# target is set to "foo", then the user could use the --with-foo-dir command
944# line option.
945#
946# You may pass along additional 'include' or 'lib' defaults via the +idefault+
947# and +ldefault+ parameters, respectively.
948#
949# Note that dir_config only adds to the list of places to search for libraries
950# and include files. It does not link the libraries into your application.
951#
952def dir_config(target, idefault=nil, ldefault=nil)
953 if dir = with_config(target + "-dir", (idefault unless ldefault))
954 defaults = Array === dir ? dir : dir.split(File::PATH_SEPARATOR)
955 idefault = ldefault = nil
956 end
957
958 idir = with_config(target + "-include", idefault)
959 $arg_config.last[1] ||= "${#{target}-dir}/include"
960 ldir = with_config(target + "-lib", ldefault)
961 $arg_config.last[1] ||= "${#{target}-dir}/lib"
962
963 idirs = idir ? Array === idir ? idir : idir.split(File::PATH_SEPARATOR) : []
964 if defaults
965 idirs.concat(defaults.collect {|dir| dir + "/include"})
966 idir = ([idir] + idirs).compact.join(File::PATH_SEPARATOR)
967 end
968 unless idirs.empty?
969 idirs.collect! {|dir| "-I" + dir}
970 idirs -= Shellwords.shellwords($CPPFLAGS)
971 unless idirs.empty?
972 $CPPFLAGS = (idirs.quote << $CPPFLAGS).join(" ")
973 end
974 end
975
976 ldirs = ldir ? Array === ldir ? ldir : ldir.split(File::PATH_SEPARATOR) : []
977 if defaults
978 ldirs.concat(defaults.collect {|dir| dir + "/lib"})
979 ldir = ([ldir] + ldirs).compact.join(File::PATH_SEPARATOR)
980 end
981 $LIBPATH = ldirs | $LIBPATH
982
983 [idir, ldir]
984end
985
986def pkg_config(pkg)
987 if pkgconfig = with_config("#{pkg}-config") and find_executable0(pkgconfig)
988 # iff package specific config command is given
989 get = proc {|opt| `#{pkgconfig} --#{opt}`.chomp}
990 elsif ($PKGCONFIG ||=
991 (pkgconfig = with_config("pkg-config", ("pkg-config" unless CROSS_COMPILING))) &&
992 find_executable0(pkgconfig) && pkgconfig) and
993 system("#{$PKGCONFIG} --exists #{pkg}")
994 # default to pkg-config command
995 get = proc {|opt| `#{$PKGCONFIG} --#{opt} #{pkg}`.chomp}
996 elsif find_executable0(pkgconfig = "#{pkg}-config")
997 # default to package specific config command, as a last resort.
998 get = proc {|opt| `#{pkgconfig} --#{opt}`.chomp}
999 end
1000 if get
1001 cflags = get['cflags']
1002 ldflags = get['libs']
1003 libs = get['libs-only-l']
1004 ldflags = (Shellwords.shellwords(ldflags) - Shellwords.shellwords(libs)).quote.join(" ")
1005 $CFLAGS += " " << cflags
1006 $LDFLAGS += " " << ldflags
1007 $libs += " " << libs
1008 Logging::message "package configuration for %s\n", pkg
1009 Logging::message "cflags: %s\nldflags: %s\nlibs: %s\n\n",
1010 cflags, ldflags, libs
1011 [cflags, ldflags, libs]
1012 else
1013 Logging::message "package configuration for %s is not found\n", pkg
1014 nil
1015 end
1016end
1017
1018def with_destdir(dir)
1019 dir = dir.sub($dest_prefix_pattern, '')
1020 /\A\$[\(\{]/ =~ dir ? dir : "$(DESTDIR)"+dir
1021end
1022
1023def winsep(s)
1024 s.tr('/', '\\')
1025end
1026
1027def configuration(srcdir)
1028 mk = []
1029 vpath = %w[$(srcdir) $(topdir) $(hdrdir)]
1030 if !CROSS_COMPILING
1031 case CONFIG['build_os']
1032 when 'cygwin'
1033 if CONFIG['target_os'] != 'cygwin'
1034 vpath.each {|p| p.sub!(/.*/, '$(shell cygpath -u \&)')}
1035 end
1036 when 'msdosdjgpp', 'mingw32'
1037 CONFIG['PATH_SEPARATOR'] = ';'
1038 end
1039 end
1040 mk << %{
1041SHELL = /bin/sh
1042
1043#### Start of system configuration section. ####
1044
1045srcdir = #{srcdir.gsub(/\$\((srcdir)\)|\$\{(srcdir)\}/) {CONFIG[$1||$2]}.quote}
1046topdir = #{($extmk ? CONFIG["topdir"] : $topdir).quote}
1047hdrdir = #{$extmk ? CONFIG["hdrdir"].quote : '$(topdir)'}
1048VPATH = #{vpath.join(CONFIG['PATH_SEPARATOR'])}
1049}
1050 if destdir = CONFIG["prefix"][$dest_prefix_pattern, 1]
1051 mk << "\nDESTDIR = #{destdir}\n"
1052 end
1053 CONFIG.each do |key, var|
1054 next unless /prefix$/ =~ key
1055 mk << "#{key} = #{with_destdir(var)}\n"
1056 end
1057 CONFIG.each do |key, var|
1058 next if /^abs_/ =~ key
1059 next unless /^(?:src|top|hdr|(.*))dir$/ =~ key and $1
1060 mk << "#{key} = #{with_destdir(var)}\n"
1061 end
1062 if !$extmk and !$configure_args.has_key?('--ruby') and
1063 sep = config_string('BUILD_FILE_SEPARATOR')
1064 sep = ":/=#{sep}"
1065 else
1066 sep = ""
1067 end
1068 extconf_h = $extconf_h ? "-DRUBY_EXTCONF_H=\\\"$(RUBY_EXTCONF_H)\\\" " : $defs.join(" ")<<" "
1069 mk << %{
1070CC = #{CONFIG['CC']}
1071LIBRUBY = #{CONFIG['LIBRUBY']}
1072LIBRUBY_A = #{CONFIG['LIBRUBY_A']}
1073LIBRUBYARG_SHARED = #$LIBRUBYARG_SHARED
1074LIBRUBYARG_STATIC = #$LIBRUBYARG_STATIC
1075
1076RUBY_EXTCONF_H = #{$extconf_h}
1077CFLAGS = #{$static ? '' : CONFIG['CCDLFLAGS']} #$CFLAGS #$ARCH_FLAG
1078INCFLAGS = -I. #$INCFLAGS
1079CPPFLAGS = #{extconf_h}#{$CPPFLAGS}
1080CXXFLAGS = $(CFLAGS) #{CONFIG['CXXFLAGS']}
1081DLDFLAGS = #$LDFLAGS #$DLDFLAGS #$ARCH_FLAG
1082LDSHARED = #{CONFIG['LDSHARED']}
1083AR = #{CONFIG['AR']}
1084EXEEXT = #{CONFIG['EXEEXT']}
1085
1086RUBY_INSTALL_NAME = #{CONFIG['RUBY_INSTALL_NAME']}
1087RUBY_SO_NAME = #{CONFIG['RUBY_SO_NAME']}
1088arch = #{CONFIG['arch']}
1089sitearch = #{CONFIG['sitearch']}
1090ruby_version = #{Config::CONFIG['ruby_version']}
1091ruby = #{$ruby}
1092RUBY = $(ruby#{sep})
1093RM = #{config_string('RM') || '$(RUBY) -run -e rm -- -f'}
1094MAKEDIRS = #{config_string('MAKEDIRS') || '@$(RUBY) -run -e mkdir -- -p'}
1095INSTALL = #{config_string('INSTALL') || '@$(RUBY) -run -e install -- -vp'}
1096INSTALL_PROG = #{config_string('INSTALL_PROG') || '$(INSTALL) -m 0755'}
1097INSTALL_DATA = #{config_string('INSTALL_DATA') || '$(INSTALL) -m 0644'}
1098COPY = #{config_string('CP') || '@$(RUBY) -run -e cp -- -v'}
1099
1100#### End of system configuration section. ####
1101
1102preload = #{$preload ? $preload.join(' ') : ''}
1103}
1104 if $nmake == ?b
1105 mk.each do |x|
1106 x.gsub!(/^(MAKEDIRS|INSTALL_(?:PROG|DATA))+\s*=.*\n/) do
1107 "!ifndef " + $1 + "\n" +
1108 $& +
1109 "!endif\n"
1110 end
1111 end
1112 end
1113 mk
1114end
1115
1116def dummy_makefile(srcdir)
1117 configuration(srcdir) << <<RULES << CLEANINGS
1118CLEANFILES = #{$cleanfiles.join(' ')}
1119DISTCLEANFILES = #{$distcleanfiles.join(' ')}
1120
1121all install static install-so install-rb: Makefile
1122
1123RULES
1124end
1125
1126# Generates the Makefile for your extension, passing along any options and
1127# preprocessor constants that you may have generated through other methods.
1128#
1129# The +target+ name should correspond the name of the global function name
1130# defined within your C extension, minus the 'Init_'. For example, if your
1131# C extension is defined as 'Init_foo', then your target would simply be 'foo'.
1132#
1133# If any '/' characters are present in the target name, only the last name
1134# is interpreted as the target name, and the rest are considered toplevel
1135# directory names, and the generated Makefile will be altered accordingly to
1136# follow that directory structure.
1137#
1138# For example, if you pass 'test/foo' as a target name, your extension will
1139# be installed under the 'test' directory. This means that in order to
1140# load the file within a Ruby program later, that directory structure will
1141# have to be followed, e.g. "require 'test/foo'".
1142#
1143def create_makefile(target, srcprefix = nil)
1144 $target = target
1145 libpath = $DEFLIBPATH|$LIBPATH
1146 message "creating Makefile\n"
1147 rm_f "conftest*"
1148 if CONFIG["DLEXT"] == $OBJEXT
1149 for lib in libs = $libs.split
1150 lib.sub!(/-l(.*)/, %%"lib\\1.#{$LIBEXT}"%)
1151 end
1152 $defs.push(format("-DEXTLIB='%s'", libs.join(",")))
1153 end
1154
1155 if target.include?('/')
1156 target_prefix, target = File.split(target)
1157 target_prefix[0,0] = '/'
1158 else
1159 target_prefix = ""
1160 end
1161
1162 srcprefix ||= '$(srcdir)'
1163 Config::expand(srcdir = srcprefix.dup)
1164
1165 if not $objs
1166 $objs = []
1167 srcs = Dir[File.join(srcdir, "*.{#{SRC_EXT.join(%q{,})}}")]
1168 for f in srcs
1169 obj = File.basename(f, ".*") << ".o"
1170 $objs.push(obj) unless $objs.index(obj)
1171 end
1172 elsif !(srcs = $srcs)
1173 srcs = $objs.collect {|obj| obj.sub(/\.o\z/, '.c')}
1174 end
1175 $srcs = srcs
1176 for i in $objs
1177 i.sub!(/\.o\z/, ".#{$OBJEXT}")
1178 end
1179 $objs = $objs.join(" ")
1180
1181 target = nil if $objs == ""
1182
1183 if target and EXPORT_PREFIX
1184 if File.exist?(File.join(srcdir, target + '.def'))
1185 deffile = "$(srcdir)/$(TARGET).def"
1186 unless EXPORT_PREFIX.empty?
1187 makedef = %{-pe "sub!(/^(?=\\w)/,'#{EXPORT_PREFIX}') unless 1../^EXPORTS$/i"}
1188 end
1189 else
1190 makedef = %{-e "puts 'EXPORTS', '#{EXPORT_PREFIX}Init_$(TARGET)'"}
1191 end
1192 if makedef
1193 $distcleanfiles << '$(DEFFILE)'
1194 origdef = deffile
1195 deffile = "$(TARGET)-$(arch).def"
1196 end
1197 end
1198 origdef ||= ''
1199
1200 libpath = libpathflag(libpath)
1201
1202 dllib = target ? "$(TARGET).#{CONFIG['DLEXT']}" : ""
1203 staticlib = target ? "$(TARGET).#$LIBEXT" : ""
1204 mfile = open("Makefile", "wb")
1205 mfile.print configuration(srcprefix)
1206 mfile.print "
1207libpath = #{($DEFLIBPATH|$LIBPATH).join(" ")}
1208LIBPATH = #{libpath}
1209DEFFILE = #{deffile}
1210
1211CLEANFILES = #{$cleanfiles.join(' ')}
1212DISTCLEANFILES = #{$distcleanfiles.join(' ')}
1213
1214extout = #{$extout}
1215extout_prefix = #{$extout_prefix}
1216target_prefix = #{target_prefix}
1217LOCAL_LIBS = #{$LOCAL_LIBS}
1218LIBS = #{$LIBRUBYARG} #{$libs} #{$LIBS}
1219SRCS = #{srcs.collect(&File.method(:basename)).join(' ')}
1220OBJS = #{$objs}
1221TARGET = #{target}
1222DLLIB = #{dllib}
1223EXTSTATIC = #{$static || ""}
1224STATIC_LIB = #{staticlib unless $static.nil?}
1225#{!$extout && defined?($installed_list) ? "INSTALLED_LIST = #{$installed_list}\n" : ""}
1226"
1227 install_dirs.each {|d| mfile.print("%-14s= %s\n" % d) if /^[[:upper:]]/ =~ d[0]}
1228 n = ($extout ? '$(RUBYARCHDIR)/' : '') + '$(TARGET).'
1229 mfile.print "
1230TARGET_SO = #{($extout ? '$(RUBYARCHDIR)/' : '')}$(DLLIB)
1231CLEANLIBS = #{n}#{CONFIG['DLEXT']} #{n}il? #{n}tds #{n}map
1232CLEANOBJS = *.#{$OBJEXT} *.#{$LIBEXT} *.s[ol] *.pdb *.exp *.bak
1233
1234all: #{$extout ? "install" : target ? "$(DLLIB)" : "Makefile"}
1235static: $(STATIC_LIB)#{$extout ? " install-rb" : ""}
1236"
1237 mfile.print CLEANINGS
1238 dirs = []
1239 mfile.print "install: install-so install-rb\n\n"
1240 sodir = (dir = "$(RUBYARCHDIR)").dup
1241 mfile.print("install-so: #{dir}\n")
1242 if target
1243 f = "$(DLLIB)"
1244 dest = "#{dir}/#{f}"
1245 mfile.print "install-so: #{dest}\n"
1246 unless $extout
1247 mfile.print "#{dest}: #{f}\n"
1248 if (sep = config_string('BUILD_FILE_SEPARATOR'))
1249 f.gsub!("/", sep)
1250 dir.gsub!("/", sep)
1251 sep = ":/="+sep
1252 f.gsub!(/(\$\(\w+)(\))/) {$1+sep+$2}
1253 f.gsub!(/(\$\{\w+)(\})/) {$1+sep+$2}
1254 dir.gsub!(/(\$\(\w+)(\))/) {$1+sep+$2}
1255 dir.gsub!(/(\$\{\w+)(\})/) {$1+sep+$2}
1256 end
1257 mfile.print "\t$(INSTALL_PROG) #{f} #{dir}\n"
1258 if defined?($installed_list)
1259 mfile.print "\t@echo #{dir}/#{File.basename(f)}>>$(INSTALLED_LIST)\n"
1260 end
1261 end
1262 end
1263 mfile.print("install-rb: pre-install-rb install-rb-default\n")
1264 mfile.print("install-rb-default: pre-install-rb-default\n")
1265 mfile.print("pre-install-rb: Makefile\n")
1266 mfile.print("pre-install-rb-default: Makefile\n")
1267 for sfx, i in [["-default", [["lib/**/*.rb", "$(RUBYLIBDIR)", "lib"]]], ["", $INSTALLFILES]]
1268 files = install_files(mfile, i, nil, srcprefix) or next
1269 for dir, *files in files
1270 unless dirs.include?(dir)
1271 dirs << dir
1272 mfile.print "pre-install-rb#{sfx}: #{dir}\n"
1273 end
1274 files.each do |f|
1275 dest = "#{dir}/#{File.basename(f)}"
1276 mfile.print("install-rb#{sfx}: #{dest}\n")
1277 mfile.print("#{dest}: #{f}\n\t$(#{$extout ? 'COPY' : 'INSTALL_DATA'}) ")
1278 sep = config_string('BUILD_FILE_SEPARATOR')
1279 if sep
1280 f = f.gsub("/", sep)
1281 sep = ":/="+sep
1282 f = f.gsub(/(\$\(\w+)(\))/) {$1+sep+$2}
1283 f = f.gsub(/(\$\{\w+)(\})/) {$1+sep+$2}
1284 else
1285 sep = ""
1286 end
1287 mfile.print("#{f} $(@D#{sep})\n")
1288 if defined?($installed_list) and !$extout
1289 mfile.print("\t@echo #{dest}>>$(INSTALLED_LIST)\n")
1290 end
1291 end
1292 end
1293 end
1294 dirs.unshift(sodir) if target and !dirs.include?(sodir)
1295 dirs.each {|dir| mfile.print "#{dir}:\n\t$(MAKEDIRS) $@\n"}
1296
1297 mfile.print <<-SITEINSTALL
1298
1299site-install: site-install-so site-install-rb
1300site-install-so: install-so
1301site-install-rb: install-rb
1302
1303 SITEINSTALL
1304
1305 return unless target
1306
1307 mfile.puts SRC_EXT.collect {|ext| ".path.#{ext} = $(VPATH)"} if $nmake == ?b
1308 mfile.print ".SUFFIXES: .#{SRC_EXT.join(' .')} .#{$OBJEXT}\n"
1309 mfile.print "\n"
1310
1311 CXX_EXT.each do |ext|
1312 COMPILE_RULES.each do |rule|
1313 mfile.printf(rule, ext, $OBJEXT)
1314 mfile.printf("\n\t%s\n\n", COMPILE_CXX)
1315 end
1316 end
1317 %w[c].each do |ext|
1318 COMPILE_RULES.each do |rule|
1319 mfile.printf(rule, ext, $OBJEXT)
1320 mfile.printf("\n\t%s\n\n", COMPILE_C)
1321 end
1322 end
1323
1324 mfile.print "$(RUBYARCHDIR)/" if $extout
1325 mfile.print "$(DLLIB): ", (makedef ? "$(DEFFILE) " : ""), "$(OBJS)\n"
1326 mfile.print "\t@-$(RM) $@\n"
1327 mfile.print "\t@-$(MAKEDIRS) $(@D)\n" if $extout
1328 link_so = LINK_SO.gsub(/^/, "\t")
1329 mfile.print link_so, "\n\n"
1330 unless $static.nil?
1331 mfile.print "$(STATIC_LIB): $(OBJS)\n\t"
1332 mfile.print "$(AR) #{config_string('ARFLAGS') || 'cru '}$@ $(OBJS)"
1333 config_string('RANLIB') do |ranlib|
1334 mfile.print "\n\t@-#{ranlib} $(DLLIB) 2> /dev/null || true"
1335 end
1336 end
1337 mfile.print "\n\n"
1338 if makedef
1339 mfile.print "$(DEFFILE): #{origdef}\n"
1340 mfile.print "\t$(RUBY) #{makedef} #{origdef} > $@\n\n"
1341 end
1342
1343 depend = File.join(srcdir, "depend")
1344 if File.exist?(depend)
1345 suffixes = []
1346 depout = []
1347 open(depend, "r") do |dfile|
1348 mfile.printf "###\n"
1349 cont = implicit = nil
1350 impconv = proc do
1351 COMPILE_RULES.each {|rule| depout << (rule % implicit[0]) << implicit[1]}
1352 implicit = nil
1353 end
1354 ruleconv = proc do |line|
1355 if implicit
1356 if /\A\t/ =~ line
1357 implicit[1] << line
1358 next
1359 else
1360 impconv[]
1361 end
1362 end
1363 if m = /\A\.(\w+)\.(\w+)(?:\s*:)/.match(line)
1364 suffixes << m[1] << m[2]
1365 implicit = [[m[1], m[2]], [m.post_match]]
1366 next
1367 elsif RULE_SUBST and /\A(?!\s*\w+\s*=)[$\w][^#]*:/ =~ line
1368 line.gsub!(%r"(\s)(?!\.)([^$(){}+=:\s\/\\,]+)(?=\s|\z)") {$1 + RULE_SUBST % $2}
1369 end
1370 depout << line
1371 end
1372 while line = dfile.gets()
1373 line.gsub!(/\.o\b/, ".#{$OBJEXT}")
1374 line.gsub!(/\$\(hdrdir\)\/config.h/, $config_h) if $config_h
1375 if /(?:^|[^\\])(?:\\\\)*\\$/ =~ line
1376 (cont ||= []) << line
1377 next
1378 elsif cont
1379 line = (cont << line).join
1380 cont = nil
1381 end
1382 ruleconv.call(line)
1383 end
1384 if cont
1385 ruleconv.call(cont.join)
1386 elsif implicit
1387 impconv.call
1388 end
1389 end
1390 unless suffixes.empty?
1391 mfile.print ".SUFFIXES: .", suffixes.uniq.join(" ."), "\n\n"
1392 end
1393 mfile.print depout
1394 else
1395 headers = %w[ruby.h defines.h]
1396 if RULE_SUBST
1397 headers.each {|h| h.sub!(/.*/) {|*m| RULE_SUBST % m}}
1398 end
1399 headers << $config_h if $config_h
1400 headers << "$(RUBY_EXTCONF_H)" if $extconf_h
1401 mfile.print "$(OBJS): ", headers.join(' '), "\n"
1402 end
1403
1404 $makefile_created = true
1405ensure
1406 mfile.close if mfile
1407end
1408
1409def init_mkmf(config = CONFIG)
1410 $makefile_created = false
1411 $arg_config = []
1412 $enable_shared = config['ENABLE_SHARED'] == 'yes'
1413 $defs = []
1414 $extconf_h = nil
1415 $CFLAGS = with_config("cflags", arg_config("CFLAGS", config["CFLAGS"])).dup
1416 $ARCH_FLAG = with_config("arch_flag", arg_config("ARCH_FLAG", config["ARCH_FLAG"])).dup
1417 $CPPFLAGS = with_config("cppflags", arg_config("CPPFLAGS", config["CPPFLAGS"])).dup
1418 $LDFLAGS = with_config("ldflags", arg_config("LDFLAGS", config["LDFLAGS"])).dup
1419 $INCFLAGS = "-I$(topdir) -I$(hdrdir) -I$(srcdir)"
1420 $DLDFLAGS = with_config("dldflags", arg_config("DLDFLAGS", config["DLDFLAGS"])).dup
1421 $LIBEXT = config['LIBEXT'].dup
1422 $OBJEXT = config["OBJEXT"].dup
1423 $LIBS = "#{config['LIBS']} #{config['DLDLIBS']}"
1424 $LIBRUBYARG = ""
1425 $LIBRUBYARG_STATIC = config['LIBRUBYARG_STATIC']
1426 $LIBRUBYARG_SHARED = config['LIBRUBYARG_SHARED']
1427 $DEFLIBPATH = $extmk ? ["$(topdir)"] : CROSS_COMPILING ? [] : ["$(libdir)"]
1428 $LIBPATH = []
1429 $INSTALLFILES = nil
1430
1431 $objs = nil
1432 $srcs = nil
1433 $libs = ""
1434 if $enable_shared or Config.expand(config["LIBRUBY"].dup) != Config.expand(config["LIBRUBY_A"].dup)
1435 $LIBRUBYARG = config['LIBRUBYARG']
1436 end
1437
1438 $LOCAL_LIBS = ""
1439
1440 $cleanfiles = config_string('CLEANFILES') {|s| Shellwords.shellwords(s)} || []
1441 $distcleanfiles = config_string('DISTCLEANFILES') {|s| Shellwords.shellwords(s)} || []
1442
1443 $extout ||= nil
1444 $extout_prefix ||= nil
1445
1446 $arg_config.clear
1447 dir_config("opt")
1448end
1449
1450FailedMessage = <<MESSAGE
1451Could not create Makefile due to some reason, probably lack of
1452necessary libraries and/or headers. Check the mkmf.log file for more
1453details. You may need configuration options.
1454
1455Provided configuration options:
1456MESSAGE
1457
1458def mkmf_failed(path)
1459 unless $makefile_created or File.exist?("Makefile")
1460 opts = $arg_config.collect {|t, n| "\t#{t}#{n ? "=#{n}" : ""}\n"}
1461 abort "*** #{path} failed ***\n" + FailedMessage + opts.join
1462 end
1463end
1464
1465init_mkmf
1466
1467$make = with_config("make-prog", ENV["MAKE"] || "make")
1468make, = Shellwords.shellwords($make)
1469$nmake = nil
1470case
1471when $mswin
1472 $nmake = ?m if /nmake/i =~ make
1473when $bccwin
1474 $nmake = ?b if /Borland/i =~ `#{make} -h`
1475end
1476
1477Config::CONFIG["srcdir"] = CONFIG["srcdir"] =
1478 $srcdir = arg_config("--srcdir", File.dirname($0))
1479$configure_args["--topsrcdir"] ||= $srcdir
1480if $curdir = arg_config("--curdir")
1481 Config.expand(curdir = $curdir.dup)
1482else
1483 curdir = $curdir = "."
1484end
1485unless File.expand_path(Config::CONFIG["topdir"]) == File.expand_path(curdir)
1486 CONFIG["topdir"] = $curdir
1487 Config::CONFIG["topdir"] = curdir
1488end
1489$configure_args["--topdir"] ||= $curdir
1490$ruby = arg_config("--ruby", File.join(Config::CONFIG["bindir"], CONFIG["ruby_install_name"]))
1491
1492split = Shellwords.method(:shellwords).to_proc
1493
1494EXPORT_PREFIX = config_string('EXPORT_PREFIX') {|s| s.strip}
1495
1496hdr = []
1497config_string('COMMON_MACROS') do |s|
1498 Shellwords.shellwords(s).each do |w|
1499 hdr << "#define " + w.split(/=/, 2).join(" ")
1500 end
1501end
1502config_string('COMMON_HEADERS') do |s|
1503 Shellwords.shellwords(s).each {|s| hdr << "#include <#{s}>"}
1504end
1505COMMON_HEADERS = hdr.join("\n")
1506COMMON_LIBS = config_string('COMMON_LIBS', &split) || []
1507
1508COMPILE_RULES = config_string('COMPILE_RULES', &split) || %w[.%s.%s:]
1509RULE_SUBST = config_string('RULE_SUBST')
1510COMPILE_C = config_string('COMPILE_C') || '$(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) -c $<'
1511COMPILE_CXX = config_string('COMPILE_CXX') || '$(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) -c $<'
1512TRY_LINK = config_string('TRY_LINK') ||
1513 "$(CC) #{OUTFLAG}conftest $(INCFLAGS) $(CPPFLAGS) " \
1514 "$(CFLAGS) $(src) $(LIBPATH) $(LDFLAGS) $(ARCH_FLAG) $(LOCAL_LIBS) $(LIBS)"
1515LINK_SO = config_string('LINK_SO') ||
1516 if CONFIG["DLEXT"] == $OBJEXT
1517 "ld $(DLDFLAGS) -r -o $@ $(OBJS)\n"
1518 else
1519 "$(LDSHARED) $(DLDFLAGS) $(LIBPATH) #{OUTFLAG}$@ " \
1520 "$(OBJS) $(LOCAL_LIBS) $(LIBS)"
1521 end
1522LIBPATHFLAG = config_string('LIBPATHFLAG') || ' -L"%s"'
1523RPATHFLAG = config_string('RPATHFLAG') || ''
1524LIBARG = config_string('LIBARG') || '-l%s'
1525
1526sep = config_string('BUILD_FILE_SEPARATOR') {|sep| ":/=#{sep}" if sep != "/"} || ""
1527CLEANINGS = "
1528clean:
1529 @-$(RM) $(CLEANLIBS#{sep}) $(CLEANOBJS#{sep}) $(CLEANFILES#{sep})
1530
1531distclean: clean
1532 @-$(RM) Makefile $(RUBY_EXTCONF_H) conftest.* mkmf.log
1533 @-$(RM) core ruby$(EXEEXT) *~ $(DISTCLEANFILES#{sep})
1534
1535realclean: distclean
1536"
1537
1538if not $extmk and /\A(extconf|makefile).rb\z/ =~ File.basename($0)
1539 END {mkmf_failed($0)}
1540end
Note: See TracBrowser for help on using the repository browser.