Typically cross-platform Apis develop code specifically for each platform and do not check has run time. The code is only specified at compile time for a target platform.
For this, they usually define macros to verify which OS it is.
Is what the Qt and the wxWidgets do.
In the header of your API you define:
#ifdef defined(__WIN32__) || defined(__NT__)
# define MEU_API_WINDOWS
# endif
#if defined(__linux__) || defined(__linux)
# define MEU_API_LINUX
#endif
#if defined(__APPLE__)
# defined MEU_API_OSX
#endif
void foo();
Hence you can define your code as follows:
void foo()
{
#if defined(MEU_API_WINDOWS)
// código para windows
#elif defined(MEU_API_LINUX)
// código para linux
#elif defined(MEU_API_OSX)
// código para OS X.
#endif
// etc
}
And with that you would need a single header and the foo() function would work on all platforms you planned.
Alternatively, you can set foo() in files. c different for each platform (gets more organized), doing the OS checks on each file.
For example, for the foo_linux.c
:
#ifdef MEU_API_LINUX
#include <lib_do_linux.h>
void foo()
{
// TODO
}
#endif
And in the foo_windows.c
:
#ifdef MEU_API_WINDOWS
#include <lib_do_windows.h>
void foo()
{
// TODO
}
#endif
I recommend you take a look at the implementations of Qt and wxWidgets as both handle this situation well.
Interesting Miguel Angelo as the suggestion of Makefile?
– Filipe
Inside the Makefile you will see the commands inside (e. g.
gcc -o foo.o foo.c
if you are using GCC) then just add in the command-d $(NOME_OS)
reference, there would be a batchfile to start make on each OS: Win32.bat => make NOME_OS=WIN32; win-phone.bat => make NOME_OS=WINPHONE... reference and so on– Miguel Angelo
But this does not prevent me from having to create a file for each platform =/ which in case would be the batch file.
– Filipe
No avoids, but it already makes the maintenance of these files absurdly simple... wants to support a new OS, just create a super-simple BATCH file. Otherwise, you will be at the mercy of the compiler defining the directives as _WINXX, __linux. Unless there is a command-line detector capable of doing this, and it is ported to the most diverse operating systems.
– Miguel Angelo
My answer was confused... I edited it.
– Miguel Angelo