Extended maintenance of Ruby versions 1.8.7 and 1.9.2 ended on July 31, 2014. Read more
BasicObject
Returns the size of the given type
. You may optionally
specify additional headers
to search in for the
type
.
If found, a macro is passed as a preprocessor constant to the compiler using the type name, in uppercase, prepended with 'SIZEOF_', followed by the type name, followed by '=X' where 'X' is the actual size.
For example, if #check_sizeof('mystruct') returned 12, then the SIZEOF_MYSTRUCT=12 preprocessor macro would be passed to the compiler.
# File mkmf.rb, line 912 def check_sizeof(type, headers = nil, &b) expr = "sizeof(#{type})" fmt = "%d" def fmt.%(x) x ? super : "failed" end checking_for checking_message("size of #{type}", headers), fmt do if size = try_constant(expr, headers, &b) $defs.push(format("-DSIZEOF_%s=%d", type.tr_cpp, size)) size end end end
Generates a header file consisting of the various macro definitions
generated by other methods such as #have_func and have_header. These
are then wrapped in a custom ifndef based on the header
file
name, which defaults to 'extconf.h'.
For example:
# extconf.rb require 'mkmf' have_func('realpath') have_header('sys/utime.h') create_header create_makefile('foo')
The above script would generate the following extconf.h file:
#ifndef EXTCONF_H #define EXTCONF_H #define HAVE_REALPATH 1 #define HAVE_SYS_UTIME_H 1 #endif
Given that the #create_header method generates a file based on definitions set earlier in your extconf.rb file, you will probably want to make this one of the last methods you call in your script.
# File mkmf.rb, line 1120 def create_header(header = "extconf.h") message "creating %s\n", header sym = header.tr("a-z./\055", "A-Z___") hdr = ["#ifndef #{sym}\n#define #{sym}\n"] for line in $defs case line when /^-D([^=]+)(?:=(.*))?/ hdr << "#define #$1 #{$2 ? Shellwords.shellwords($2)[0] : 1}\n" when /^-U(.*)/ hdr << "#undef #$1\n" end end hdr << "#endif\n" hdr = hdr.join unless (IO.read(header) == hdr rescue false) open(header, "w") do |hfile| hfile.write(hdr) end end $extconf_h = header end
Generates the Makefile for your extension, passing along any options and preprocessor constants that you may have generated through other methods.
The target
name should correspond the name of the global
function name defined within your C extension, minus the 'Init_'.
For example, if your C extension is defined as 'Init_foo', then
your target would simply be 'foo'.
If any '/' characters are present in the target name, only the last name is interpreted as the target name, and the rest are considered toplevel directory names, and the generated Makefile will be altered accordingly to follow that directory structure.
For example, if you pass 'test/foo' as a target name, your extension will be installed under the 'test' directory. This means that in order to load the file within a Ruby program later, that directory structure will have to be followed, e.g. “require 'test/foo'”.
The srcprefix
should be used when your source files are not in
the same directory as your build script. This will not only eliminate the
need for you to manually copy the source files into the same directory as
your build script, but it also sets the proper target_prefix
in the generated Makefile.
Setting the target_prefix
will, in turn, install the generated
binary in a directory under your Config::CONFIG
that mimics your local filesystem when you run 'make install'.
For example, given the following file tree:
ext/ extconf.rb test/ foo.c
And given the following code:
create_makefile('test/foo', 'test')
That will set the target_prefix
in the generated Makefile to
'test'. That, in turn, will create the following file tree when
installed via the 'make install' command:
/path/to/ruby/sitearchdir/test/foo.so
It is recommended that you use this approach to generate your makefiles,
instead of copying files around manually, because some third party
libraries may depend on the target_prefix
being set properly.
The srcprefix
argument can be used to override the default
source directory, i.e. the current directory . It is included as part of
the VPATH and added to the list of INCFLAGS.
# File mkmf.rb, line 1422 def create_makefile(target, srcprefix = nil) $target = target libpath = $DEFLIBPATH|$LIBPATH message "creating Makefile\n" rm_f "conftest*" if CONFIG["DLEXT"] == $OBJEXT for lib in libs = $libs.split lib.sub!(/-l(.*)/, %%"lib\\1.#{$LIBEXT}"%) end $defs.push(format("-DEXTLIB='%s'", libs.join(","))) end if target.include?('/') target_prefix, target = File.split(target) target_prefix[0,0] = '/' else target_prefix = "" end srcprefix ||= '$(srcdir)' Config::expand(srcdir = srcprefix.dup) if not $objs $objs = [] srcs = Dir[File.join(srcdir, "*.{#{SRC_EXT.join(%q{,})}}")] for f in srcs obj = File.basename(f, ".*") << ".o" $objs.push(obj) unless $objs.index(obj) end elsif !(srcs = $srcs) srcs = $objs.collect {|obj| obj.sub(/\.o\z/, '.c')} end $srcs = srcs for i in $objs i.sub!(/\.o\z/, ".#{$OBJEXT}") end $objs = $objs.join(" ") target = nil if $objs == "" if target and EXPORT_PREFIX if File.exist?(File.join(srcdir, target + '.def')) deffile = "$(srcdir)/$(TARGET).def" unless EXPORT_PREFIX.empty? makedef = %{-pe "sub!(/^(?=\\w)/,'#{EXPORT_PREFIX}') unless 1../^EXPORTS$/i"} end else makedef = %{-e "puts 'EXPORTS', '#{EXPORT_PREFIX}Init_$(TARGET)'"} end if makedef $distcleanfiles << '$(DEFFILE)' origdef = deffile deffile = "$(TARGET)-$(arch).def" end end origdef ||= '' libpath = libpathflag(libpath) dllib = target ? "$(TARGET).#{CONFIG['DLEXT']}" : "" staticlib = target ? "$(TARGET).#$LIBEXT" : "" mfile = open("Makefile", "wb") mfile.print configuration(srcprefix) mfile.print " libpath = #{($DEFLIBPATH|$LIBPATH).join(" ")} LIBPATH = #{libpath} DEFFILE = #{deffile} CLEANFILES = #{$cleanfiles.join(' ')} DISTCLEANFILES = #{$distcleanfiles.join(' ')} extout = #{$extout} extout_prefix = #{$extout_prefix} target_prefix = #{target_prefix} LOCAL_LIBS = #{$LOCAL_LIBS} LIBS = #{$LIBRUBYARG} #{$libs} #{$LIBS} SRCS = #{srcs.collect(&File.method(:basename)).join(' ')} OBJS = #{$objs} TARGET = #{target} DLLIB = #{dllib} EXTSTATIC = #{$static || ""} STATIC_LIB = #{staticlib unless $static.nil?} #{!$extout && defined?($installed_list) ? "INSTALLED_LIST = #{$installed_list}\n" : ""} " install_dirs.each {|d| mfile.print("%-14s= %s\n" % d) if /^[[:upper:]]/ =~ d[0]} n = ($extout ? '$(RUBYARCHDIR)/' : '') + '$(TARGET).' mfile.print " TARGET_SO = #{($extout ? '$(RUBYARCHDIR)/' : '')}$(DLLIB) CLEANLIBS = #{n}#{CONFIG['DLEXT']} #{n}il? #{n}tds #{n}map CLEANOBJS = *.#{$OBJEXT} *.#{$LIBEXT} *.s[ol] *.pdb *.exp *.bak all: #{$extout ? "install" : target ? "$(DLLIB)" : "Makefile"} static: $(STATIC_LIB)#{$extout ? " install-rb" : ""} " mfile.print CLEANINGS dirs = [] mfile.print "install: install-so install-rb\n\n" sodir = (dir = "$(RUBYARCHDIR)").dup mfile.print("install-so: ") if target f = "$(DLLIB)" dest = "#{dir}/#{f}" mfile.puts dir, "install-so: #{dest}" unless $extout mfile.print "#{dest}: #{f}\n" if (sep = config_string('BUILD_FILE_SEPARATOR')) f.gsub!("/", sep) dir.gsub!("/", sep) sep = ":/="+sep f.gsub!(/(\$\(\w+)(\))/) {$1+sep+$2} f.gsub!(/(\$\{\w+)(\})/) {$1+sep+$2} dir.gsub!(/(\$\(\w+)(\))/) {$1+sep+$2} dir.gsub!(/(\$\{\w+)(\})/) {$1+sep+$2} end mfile.print "\t$(INSTALL_PROG) #{f} #{dir}\n" if defined?($installed_list) mfile.print "\t@echo #{dir}/#{File.basename(f)}>>$(INSTALLED_LIST)\n" end end else mfile.puts "Makefile" end mfile.print("install-rb: pre-install-rb install-rb-default\n") mfile.print("install-rb-default: pre-install-rb-default\n") mfile.print("pre-install-rb: Makefile\n") mfile.print("pre-install-rb-default: Makefile\n") for sfx, i in [["-default", [["lib/**/*.rb", "$(RUBYLIBDIR)", "lib"]]], ["", $INSTALLFILES]] files = install_files(mfile, i, nil, srcprefix) or next for dir, *files in files unless dirs.include?(dir) dirs << dir mfile.print "pre-install-rb#{sfx}: #{dir}\n" end files.each do |f| dest = "#{dir}/#{File.basename(f)}" mfile.print("install-rb#{sfx}: #{dest}\n") mfile.print("#{dest}: #{f} #{dir}\n\t$(#{$extout ? 'COPY' : 'INSTALL_DATA'}) ") sep = config_string('BUILD_FILE_SEPARATOR') if sep f = f.gsub("/", sep) sep = ":/="+sep f = f.gsub(/(\$\(\w+)(\))/) {$1+sep+$2} f = f.gsub(/(\$\{\w+)(\})/) {$1+sep+$2} else sep = "" end mfile.print("#{f} $(@D#{sep})\n") if defined?($installed_list) and !$extout mfile.print("\t@echo #{dest}>>$(INSTALLED_LIST)\n") end end end end dirs.unshift(sodir) if target and !dirs.include?(sodir) dirs.each {|dir| mfile.print "#{dir}:\n\t$(MAKEDIRS) $@\n"} mfile.print <<-SITEINSTALL site-install: site-install-so site-install-rb site-install-so: install-so site-install-rb: install-rb SITEINSTALL return unless target mfile.puts SRC_EXT.collect {|ext| ".path.#{ext} = $(VPATH)"} if $nmake == ?b mfile.print ".SUFFIXES: .#{SRC_EXT.join(' .')} .#{$OBJEXT}\n" mfile.print "\n" CXX_EXT.each do |ext| COMPILE_RULES.each do |rule| mfile.printf(rule, ext, $OBJEXT) mfile.printf("\n\t%s\n\n", COMPILE_CXX) end end %w[c].each do |ext| COMPILE_RULES.each do |rule| mfile.printf(rule, ext, $OBJEXT) mfile.printf("\n\t%s\n\n", COMPILE_C) end end mfile.print "$(RUBYARCHDIR)/" if $extout mfile.print "$(DLLIB): " mfile.print "$(DEFFILE) " if makedef mfile.print "$(OBJS) Makefile\n" mfile.print "\t@-$(RM) $@\n" mfile.print "\t@-$(MAKEDIRS) $(@D)\n" if $extout link_so = LINK_SO.gsub(/^/, "\t") mfile.print link_so, "\n\n" unless $static.nil? mfile.print "$(STATIC_LIB): $(OBJS)\n\t" mfile.print "$(AR) #{config_string('ARFLAGS') || 'cru '}$@ $(OBJS)" config_string('RANLIB') do |ranlib| mfile.print "\n\t@-#{ranlib} $(DLLIB) 2> /dev/null || true" end end mfile.print "\n\n" if makedef mfile.print "$(DEFFILE): #{origdef}\n" mfile.print "\t$(RUBY) #{makedef} #{origdef} > $@\n\n" end depend = File.join(srcdir, "depend") if File.exist?(depend) suffixes = [] depout = [] open(depend, "r") do |dfile| mfile.printf "###\n" cont = implicit = nil impconv = proc do COMPILE_RULES.each {|rule| depout << (rule % implicit[0]) << implicit[1]} implicit = nil end ruleconv = proc do |line| if implicit if /\A\t/ =~ line implicit[1] << line next else impconv[] end end if m = /\A\.(\w+)\.(\w+)(?:\s*:)/.match(line) suffixes << m[1] << m[2] implicit = [[m[1], m[2]], [m.post_match]] next elsif RULE_SUBST and /\A(?!\s*\w+\s*=)[$\w][^#]*:/ =~ line line.gsub!(%r"(\s)(?!\.)([^$(){}+=:\s\/\\,]+)(?=\s|\z)") {$1 + RULE_SUBST % $2} end depout << line end while line = dfile.gets() line.gsub!(/\.o\b/, ".#{$OBJEXT}") line.gsub!(/\$\((?:hdr|top)dir\)\/config.h/, $config_h) if $config_h if /(?:^|[^\\])(?:\\\\)*\\$/ =~ line (cont ||= []) << line next elsif cont line = (cont << line).join cont = nil end ruleconv.call(line) end if cont ruleconv.call(cont.join) elsif implicit impconv.call end end unless suffixes.empty? mfile.print ".SUFFIXES: .", suffixes.uniq.join(" ."), "\n\n" end mfile.print "$(OBJS): $(RUBY_EXTCONF_H)\n\n" if $extconf_h mfile.print depout else headers = %w[ruby.h defines.h] if RULE_SUBST headers.each {|h| h.sub!(/.*/) {|*m| RULE_SUBST % m}} end headers << $config_h if $config_h headers << "$(RUBY_EXTCONF_H)" if $extconf_h mfile.print "$(OBJS): ", headers.join(' '), "\n" end $makefile_created = true ensure mfile.close if mfile end
Sets a target
name that the user can then use to configure
various 'with' options with on the command line by using that name.
For example, if the target is set to “foo”, then the user could use the
–with-foo-dir command line option.
You may pass along additional 'include' or 'lib' defaults
via the idefault
and ldefault
parameters,
respectively.
Note that #dir_config only adds to the list of places to search for libraries and include files. It does not link the libraries into your application.
# File mkmf.rb, line 1153 def dir_config(target, idefault=nil, ldefault=nil) if dir = with_config(target + "-dir", (idefault unless ldefault)) defaults = Array === dir ? dir : dir.split(File::PATH_SEPARATOR) idefault = ldefault = nil end idir = with_config(target + "-include", idefault) $arg_config.last[1] ||= "${#{target}-dir}/include" ldir = with_config(target + "-lib", ldefault) $arg_config.last[1] ||= "${#{target}-dir}/lib" idirs = idir ? Array === idir ? idir : idir.split(File::PATH_SEPARATOR) : [] if defaults idirs.concat(defaults.collect {|dir| dir + "/include"}) idir = ([idir] + idirs).compact.join(File::PATH_SEPARATOR) end unless idirs.empty? idirs.collect! {|dir| "-I" + dir} idirs -= Shellwords.shellwords($CPPFLAGS) unless idirs.empty? $CPPFLAGS = (idirs.quote << $CPPFLAGS).join(" ") end end ldirs = ldir ? Array === ldir ? ldir : ldir.split(File::PATH_SEPARATOR) : [] if defaults ldirs.concat(defaults.collect {|dir| dir + "/lib"}) ldir = ([ldir] + ldirs).compact.join(File::PATH_SEPARATOR) end $LIBPATH = ldirs | $LIBPATH [idir, ldir] end
Tests for the presence of an –enable-config
or
–disable-config
option. Returns true if the enable option is
given, false if the disable option is given, and the default value
otherwise.
This can be useful for adding custom definitions, such as debug information.
Example:
if enable_config("debug") $defs.push("-DOSSL_DEBUG") unless $defs.include? "-DOSSL_DEBUG" end
# File mkmf.rb, line 1082 def enable_config(config, *defaults) if arg_config("--enable-"+config) true elsif arg_config("--disable-"+config) false elsif block_given? yield(config, *defaults) else return *defaults end end
Searches for the executable bin
on path
. The
default path is your PATH environment variable. If that isn't defined,
it will resort to searching /usr/local/bin, /usr/ucb, /usr/bin and /bin.
If found, it will return the full path, including the executable name, of where it was found.
Note that this method does not actually affect the generated Makefile.
# File mkmf.rb, line 1021 def find_executable(bin, path = nil) checking_for checking_message(bin, path) do find_executable0(bin, path) end end
Instructs mkmf to search for the given header
in any of the
paths
provided, and returns whether or not it was found in
those paths.
If the header is found then the path it was found on is added to the list of included directories that are sent to the compiler (via the -I switch).
# File mkmf.rb, line 761 def find_header(header, *paths) message = checking_message(header, paths) header = cpp_include(header) checking_for message do if try_cpp(header) true else found = false paths.each do |dir| opt = "-I#{dir}".quote if try_cpp(header, opt) $INCFLAGS << " " << opt found = true break end end found end end end
Returns whether or not the entry point func
can be found
within the library lib
in one of the paths
specified, where paths
is an array of strings. If
func
is nil , then the main() function is used as the entry
point.
If lib
is found, then the path it was found on is added to the
list of library paths searched and linked against.
# File mkmf.rb, line 677 def find_library(lib, func, *paths, &b) func = "main" if !func or func.empty? lib = with_config(lib+'lib', lib) paths = paths.collect {|path| path.split(File::PATH_SEPARATOR)}.flatten checking_for "#{func}() in #{LIBARG%lib}" do libpath = $LIBPATH libs = append_library($libs, lib) begin until r = try_func(func, libs, &b) or paths.empty? $LIBPATH = libpath | [paths.shift] end if r $libs = libs libpath = nil end ensure $LIBPATH = libpath if libpath end r end end
Returns where the static type type
is defined.
You may also pass additional flags to opt
which are then
passed along to the compiler.
See also have_type
.
# File mkmf.rb, line 851 def find_type(type, opt, *headers, &b) opt ||= "" fmt = "not found" def fmt.%(x) x ? x.respond_to?(:join) ? x.join(",") : x : self end checking_for checking_message(type, nil, opt), fmt do headers.find do |h| try_type(type, h, opt, &b) end end end
Returns whether or not the constant const
is defined. You may
optionally pass the type
of const
as
[const, type]
, like as:
have_const(%w[PTHREAD_MUTEX_INITIALIZER pthread_mutex_t], "pthread.h")
You may also pass additional headers
to check against in
addition to the common header files, and additional flags to
opt
which are then passed along to the compiler.
If found, a macro is passed as a preprocessor constant to the compiler using the type name, in uppercase, prepended with 'HAVE_CONST_'.
For example, if #have_const('foo') returned true, then the HAVE_CONST_FOO preprocessor macro would be passed to the compiler.
# File mkmf.rb, line 896 def have_const(const, headers = nil, opt = "", &b) checking_for checking_message([*const].compact.join(' '), headers, opt) do try_const(const, headers, opt, &b) end end
Returns whether or not the function func
can be found in the
common header files, or within any headers
that you provide.
If found, a macro is passed as a preprocessor constant to the compiler
using the function name, in uppercase, prepended with 'HAVE_'.
For example, if #have_func('foo') returned true, then the HAVE_FOO preprocessor macro would be passed to the compiler.
# File mkmf.rb, line 707 def have_func(func, headers = nil, &b) checking_for checking_message("#{func}()", headers) do if try_func(func, $libs, headers, &b) $defs.push(format("-DHAVE_%s", func.tr_cpp)) true else false end end end
Returns whether or not the given header
file can be found on
your system. If found, a macro is passed as a preprocessor constant to the
compiler using the header file name, in uppercase, prepended with
'HAVE_'.
For example, if #have_header('foo.h') returned true, then the HAVE_FOO_H preprocessor macro would be passed to the compiler.
# File mkmf.rb, line 744 def have_header(header, &b) checking_for header do if try_cpp(cpp_include(header), &b) $defs.push(format("-DHAVE_%s", header.tr("a-z./\055", "A-Z___"))) true else false end end end
Returns whether or not the given entry point func
can be found
within lib
. If func
is nil, the 'main()'
entry point is used by default. If found, it adds the library to list of
libraries to be used when linking your extension.
If headers
are provided, it will include those header files as
the header files it looks in when searching for func
.
The real name of the library to be linked can be altered by '–with-FOOlib' configuration option.
# File mkmf.rb, line 652 def have_library(lib, func = nil, headers = nil, &b) func = "main" if !func or func.empty? lib = with_config(lib+'lib', lib) checking_for checking_message("#{func}()", LIBARG%lib) do if COMMON_LIBS.include?(lib) true else libs = append_library($libs, lib) if try_func(func, libs, headers, &b) $libs = libs true else false end end end end
Returns whether or not macro
is defined either in the common
header files or within any headers
you provide.
Any options you pass to opt
are passed along to the compiler.
# File mkmf.rb, line 635 def have_macro(macro, headers = nil, opt = "", &b) checking_for checking_message(macro, headers, opt) do macro_defined?(macro, cpp_include(headers), opt, &b) end end
Returns whether or not the struct of type type
contains
member
. If it does not, or the struct type can't be
found, then false is returned. You may optionally specify additional
headers
in which to look for the struct (in addition to the
common header files).
If found, a macro is passed as a preprocessor constant to the compiler using the member name, in uppercase, prepended with 'HAVE_ST_'.
For example, if #have_struct_member('struct foo', 'bar') returned true, then the HAVE_ST_BAR preprocessor macro would be passed to the compiler.
# File mkmf.rb, line 793 def have_struct_member(type, member, headers = nil, &b) checking_for checking_message("#{type}.#{member}", headers) do if try_compile(<<"SRC", &b) #{COMMON_HEADERS} #{cpp_include(headers)} /*top*/ int main() { return 0; } int s = (char *)&((#{type}*)0)->#{member} - (char *)0; SRC $defs.push(format("-DHAVE_ST_%s", member.tr_cpp)) true else false end end end
Returns whether or not the static type type
is defined. You
may optionally pass additional headers
to check against in
addition to the common header files.
You may also pass additional flags to opt
which are then
passed along to the compiler.
If found, a macro is passed as a preprocessor constant to the compiler using the type name, in uppercase, prepended with 'HAVE_TYPE_'.
For example, if #have_type('foo') returned true, then the HAVE_TYPE_FOO preprocessor macro would be passed to the compiler.
# File mkmf.rb, line 838 def have_type(type, headers = nil, opt = "", &b) checking_for checking_message(type, headers, opt) do try_type(type, headers, opt, &b) end end
Returns whether or not the variable var
can be found in the
common header files, or within any headers
that you provide.
If found, a macro is passed as a preprocessor constant to the compiler
using the variable name, in uppercase, prepended with 'HAVE_'.
For example, if #have_var('foo') returned true, then the HAVE_FOO preprocessor macro would be passed to the compiler.
# File mkmf.rb, line 726 def have_var(var, headers = nil, &b) checking_for checking_message(var, headers) do if try_var(var, headers, &b) $defs.push(format("-DHAVE_%s", var.tr_cpp)) true else false end end end
# File mkmf.rb, line 864 def try_const(const, headers = nil, opt = "", &b) const, type = *const if try_compile(<<"SRC", opt, &b) #{COMMON_HEADERS} #{cpp_include(headers)} /*top*/ typedef #{type || 'int'} conftest_type; conftest_type conftestval = #{type ? '' : '(int)'}#{const}; SRC $defs.push(format("-DHAVE_CONST_%s", const.tr_cpp)) true else false end end
# File mkmf.rb, line 810 def try_type(type, headers = nil, opt = "", &b) if try_compile(<<"SRC", opt, &b) #{COMMON_HEADERS} #{cpp_include(headers)} /*top*/ typedef #{type} conftest_type; int conftestval[sizeof(conftest_type)?1:-1]; SRC $defs.push(format("-DHAVE_TYPE_%s", type.tr_cpp)) true else false end end
Tests for the presence of a –with-config
or
–without-config
option. Returns true if the with option is
given, false if the without option is given, and the default value
otherwise.
This can be useful for adding custom definitions, such as debug information.
Example:
if with_config("debug") $defs.push("-DOSSL_DEBUG") unless $defs.include? "-DOSSL_DEBUG" end
# File mkmf.rb, line 1049 def with_config(config, *defaults) config = config.sub(/^--with[-_]/, '') val = arg_config("--with-"+config) do if arg_config("--without-"+config) false elsif block_given? yield(config, *defaults) else break *defaults end end case val when "yes" true when "no" false else val end end