How to define a function in C, if not already defined?

I am writing a Ruby C Extension where I use math.h It compiles on both OSX and Windows. On Windows, I use nmake , which comes with Visual Studio Express C ++ 2010.

I found that VS did not include the round() function in my math.h So I added this to compensate:

 static inline double round( double value ) { return floor( value + 0.5 ); } 

This course caused an error when compiling under OSX as round() . (The actual error, I think, was declared by my statics after it was declared a non-static version.

Regardless, I would like to avoid overriding the function if it exists.

At the moment, I have this condition:

 #ifdef _WIN32 static inline double round( double value ) { return floor( value + 0.5 ); } #endif 

This worked in my scenario - but it seems a bit general. I mean, what if I compile with another compiler for Windows?

So my question is: can I determine if a function is defined, and then not define it myself?

Or, can I specifically define the nmake use- cl compiler nmake I think it is?

I think that ideally I could determine if this function was already defined, since it seems to be the most reliable method.

+6
source share
3 answers

I found that the Ruby mkmf utility has a have_func method that can be used to check for the existence of functions: http://apidock.com/ruby/Object/have_func

I added have_func( 'round', 'math.h' ) to my extconf.rb file, which then gave me the HAVE_ROUND preprocessor HAVE_ROUND .

Then I could safely define round (), which it did not exist:

 #ifndef HAVE_ROUND static inline double round( double value ) { return floor( value + 0.5 ); } #endif 

Worked great! :)

0
source

This worked in my scenario - but it seems a bit general. I mean, what if I compile with another compiler for Windows?

  • General is helpful.
  • It doesn't matter which compiler you use; you just check if the character is defined. You can define this symbol using any compiler, it does not matter. ifdef , usually you handle portability problems.
  • round defined by the C99 standard. VS currently does not support C99, so it is missing.
+2
source

What you did is the right way to deal with incompatibility.

You have noticed that this way of dealing with system-dependent incompatibilities is β€œnot common,” but on the contrary languages ​​like JAVA, which abstracts such problems, you have to deal with such things. On the other hand, you will always get the maximum performance offered by the platform.

0
source

Source: https://habr.com/ru/post/910277/


All Articles