How do I conditionally compile C code snippets to my Perl module?
- by mobrule
I have a module that will target several different operating systems
and configurations. Sometimes, some C code can make this module's task
a little easier, so I have some C functions that I would like to bind
the code. I don't have to bind the C functions -- I can't guarantee
that the end-user even has a C compiler, for instance, and it's generally
not a problem to failover gracefully to a pure Perl way of accomplishing
the same thing -- but it would be nice if I could call the C functions
from the Perl script.
Still with me? Here's another tricky part. Just about all of the C code
is system specific -- a function written for Windows won't compile on
Linux and vice-versa, and the function that does a similar thing on
Solaris will look totally different.
#include <some/Windows/headerfile.h>
int foo_for_Windows_c(int a,double b)
{
do_windows_stuff();
return 42;
}
#include <path/to/linux/headerfile.h>
int foo_for_linux_c(int a,double b)
{
do_linux_stuff(7);
return 42;
}
Furthermore, even for native code that targets the same system, it's
possible that only some of them can be compiled on any particular
configuration.
#include <some/headerfile/that/might/not/even/exist.h>
int bar_for_solaris_c(int a,double b)
{
call_solaris_library_that_might_be_installed_here(11);
return 19;
}
But ideally we could still use the C functions that would compile
with that configuration. So my questions are:
how can I compile C functions conditionally (compile only the code that
is appropriate for the current value of $^O)?
how can I compile C functions individually (some functions might not
compile, but we still want to use the ones that can)?
can I do this at build-time (while the end-user is installing the
module) or at run-time (with Inline::C, for example)? Which
way is better?
how would I tell which functions were successfully compiled and are
available for use from Perl?
All thoughts appreciated!