I’m writing a Ruby C Extension where I’m using math.h. It’s being compiled on both OSX and Windows. Under Windows I use nmake that comes with Visual Studio Express C++ 2010.
I found that VS didn’t include the round() function in their math.h. So I added this to compensate:
static inline double round( double value )
{
return floor( value + 0.5 );
}
That off course caused an error when compiling under OSX as round() there is defined. (The actual error I think was that I’d declared mine static after it’s already been declared a non-static version.
Regardless, I’d like to avoid redefining the function if it does exist.
At the moment I have this conditional:
#ifdef _WIN32
static inline double round( double value )
{
return floor( value + 0.5 );
}
#endif
That worked in my scenario – but it seem a bit generic. I mean, what if I compile with a different compiler under Windows?
So my question is, can I detect if a function is already defined, and then avoid defining it myself?
Or, can I detect specifically the compiler nmake use – cl I think it is?
I’m thinking I’d ideally be able to detect if the function is already defined, as it seem like the most robust method.
I found that Ruby’s mkmf utility has a method
have_functhat one can use to check for the existence of functions: http://apidock.com/ruby/Object/have_funcI added
have_func( 'round', 'math.h' )to myextconf.rbfile which then gave me aHAVE_ROUNDpreprocessor constant.Then I could safely define round() myself it it didn’t exist:
Worked perfectly! 🙂