How can I call functions in a different C source file from a Perl XS module?
This is actually rather straightforward:
hello.h
#ifndef H_HELLO
const char *hello(void);
#define H_HELLO
#endif
hello.c
const char *
hello(void) {
return "Hello";
}
Example.xs
#define PERL_NO_GET_CONTEXT
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"
#include "ppport.h"
#include "hello.h"
MODULE = My::Example PACKAGE = My::Example PREFIX = MY_
PROTOTYPES: DISABLE
const char *
MY_hello()
CODE:
RETVAL = hello();
OUTPUT:
RETVAL
t/My-Example.t
use strict;
use warnings;
use Test::More;
BEGIN { use_ok('My::Example') };
is(My::Example::hello(), 'Hello', 'hello returns "Hello"');
done_testing;
[~/tmp/My-Example]$ prove -vb t/My-Example.t t/My-Example.t .. ok 1 - use My::Example; ok 2 - hello returns "Hello" 1..2 ok All tests successful. Files=1, Tests=2, 0 wallclock secs ( 0.04 usr 0.01 sys + 0.03 cusr 0.00 csys = 0.08 CPU) Result: PASS
The Makefile.PL
was generated by h2xs
. The only thing I changed was to uncomment the following line:
# Un-comment this if you add C files to link with later: OBJECT => '$(O_FILES)', # link all the C files too