Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a system implements a function

I'm creating a cross-system application. It uses, for example, the function itoa, which is implemented on some systems but not all. If I simply provide my own itoa implementation:

header.h:115:13: error: conflicting types for 'itoa'
 extern void itoa(int, char[]);

In file included from header.h:2:0,
                 from file.c:2:0,
c:\path\to\mingw\include\stdlib.h:631:40: note: previous declaration of 'itoa' was here
 _CRTIMP __cdecl __MINGW_NOTHROW  char* itoa (int, char*, int);

I know I can check if macros are predefined and define them if not:

#ifndef _SOME_MACRO
#define _SOME_MACRO 45
#endif

Is there a way to check if a C function is pre-implemented, and if not, implement it? Or to simply un-implement a function?

like image 575
MD XF Avatar asked Feb 18 '17 03:02

MD XF


2 Answers

Given you have already written your own implementation of itoa(), I would recommend that you rename it and use it everywhere. At least you are sure you will get the same behavior on all platforms, and avoid the linking issue.

Don't forget to explain your choice in the comments of your code...

like image 169
Heyji Avatar answered Oct 06 '22 04:10

Heyji


I assume you are using GCC, as I can see MinGW in your path... there's one way the GNU linker can take care of this for you. So you don't know whether there is an itoa implementation or not. Try this:

Create a new file (without any headers) called my_itoa.c:

char *itoa (int, char *, int);

char *my_itoa (int a, char *b, int c)
{
    return itoa(a, b, c);
}

Now create another file, impl_itoa.c. Here, write the implementation of itoa but add a weak alias:

char* __attribute__ ((weak)) itoa(int a, char *b, int c)
{
     // implementation here
}

Compile all of the files, with impl_itoa.c at the end.

This way, if itoa is not available in the standard library, this one will be linked. You can be confident about it compiling whether or not it's available.

like image 33
Ajay Brahmakshatriya Avatar answered Oct 06 '22 03:10

Ajay Brahmakshatriya