Kevin Sylvestre
Kevin Sylvestre

Reputation: 38012

Native C Extension if Library is Available

I'm building a native C extension Ruby gem for generating unique identifiers (found here). I'd like the library to use libuuid if possible (through C extensions) and fall back to a simple Ruby implementation. I currently have both the C and Ruby code for generating the UUID, however I can't figure out how to configure a successful fallback. Any ideas?

Upvotes: 4

Views: 247

Answers (1)

mu is too short
mu is too short

Reputation: 434635

The have_library method has a return value:

Returns whether or not the given entry point func can be found within lib.

So you should be able to do this:

$defs.push('-DUSE_RUBY_UUID') if !have_library('uuid')
create_makefile("identifier")

And then set up your C to use libuuid if USE_RUBY_UUID is not defined and call into the Ruby UUID library if it is defined.

Oddly enough, the have_header and have_func methods in mkmf.rb add macros for you:

# File mkmf.rb, line 840
def have_header(header, preheaders = nil, &b)
  checking_for header do
    if try_header(cpp_include(preheaders)+cpp_include(header), &b)
      $defs.push(format("-DHAVE_%s", header.tr_cpp))
      true
    else
      false
    end
  end
end

but have_library makes you do it yourself.

Upvotes: 3

Related Questions