Using h2xs to Make a Module with C Code

Problem

You’d like to access your system’s unique C functions from Perl.

Solution

Use the h2xs tool to generate the necessary template files, fill the files in appropriately, and then type:

% perl Makefile.PL
% make

Discussion

A Perl module need not be written solely in Perl. As with any other module, first pick a module name and use h2xs on it. We’ll make a FineTime::time function with the same semantics as in the previous recipe, but this time around, we’ll implement it using real C.

First, we run the following command:

% h2xs -cn FineTime

If we had a .h file with function prototype declarations, we could include that, but because we’re writing this one from scratch, we’ll use the -c flag to omit building code to translate any #define symbols. The -n flag says to create a module directory named FineTime/, which will have the following files:

Manifest

List of files in the distribution

Changes

change log

Makefile.PL

a meta-makefile

FineTime.pm

the Perl parts

FineTime.xs

the soon-to-be C parts

test.pl

a test driver

Before we can type make, we’ll have to generate a Makefile based on our system’s configuration using the Makefile.PL template. Here’s how to do that:

% perl Makefile.PL

If the XS code calls library code that isn’t in the normal set of libraries Perl links from, add one more line to Makefile.PL first. For example, if we wanted to link against the librpm.a library, which lives in the /usr/redhat/lib directory, we’d ...

Get Perl Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.