halfcountplus has asked for the wisdom of the Perl Monks concerning the following question:

I'm working on an XS module and I'd like to be able to test code by just compiling a C file. However, including EXTERN.h, perl.h, and XSUB.h does not cut the mustard; some of the "undefined references" lead only to binary files, so perhaps there is something I have to feed the linker here? The stuff I've found online only discusses using h2xs and the whole build process. I'm assuming that is not necessary if the executable is not really a perl module (it's just using the api)?

Replies are listed 'Best First'.
Re: Using the perl API in C
by Anonyrnous Monk (Hermit) on Dec 20, 2010 at 19:22 UTC
    perhaps there is something I have to feed the linker here?

    -lperl, i.e. link against the perl library (either libperl.so or libperl.a (static) — if the linker finds both, the shared version takes precedence by default). Whether that's sufficient depends on what exactly you're trying to do.

    See also perlembed.

      In fact "-lperl" was my first guess, but that was not found. I didn't realize it was in a non-standard path, so I added "-L/usr/lib64/perl5/5.10.0/x86_64-linux-thread-multi/CORE"; of course it's then not found at runtime, so I added a softlink into /usr/lib64.

      But now I'm getting segfaults on basic stuff that worked fine in an XS module. Eg:

      SV *r = newSVpv("hello world\0", 16);

      Leads to:
      Program received signal SIGSEGV, Segmentation fault.
      Perl_newSVpv (my_perl=0x0, s=0x400848 "hello world", len=16) at sv.c:6985
      6985 new_SV(sv);

      Grrrr....

        You'll probably also have to initialise the interpreter (perl_alloc(), perl_construct() - see perlembed for details), so memory management works.

        If you provide a self-contained sample of what you're trying to build, someone here might look into getting it to run... :)

Re: Using the perl API in C
by ikegami (Patriarch) on Dec 20, 2010 at 20:06 UTC

    so perhaps there is something I have to feed the linker here?

    Yes. You are using Perl, so you'll need to link in Perl.

    It's up to you whether you rely on Perl or not. Take for example XML::LibXML. The real work is done by pure C or C++ code that knows nothing of Perl. The only C code that knows of Perl is glue code, the interface.

    If you follow that model*, you can test the underlying guts without using Perl. I think this is what you desire.

    * — XML::LibXML's guts is a separate install, but you don't have to go that far if you don't want to.

Re: Using the perl API in C
by andal (Hermit) on Dec 21, 2010 at 10:15 UTC

    Well, if you want to test only your C code without testing the glue between your code and perl, then just separate the library and the glue.

    If the question was really about the link-time flags, then other comments provide good answers.