LinuxCommandLibrary

h2ph

Convert C header files to Perl equivalents

SYNOPSIS

h2ph [-d directory] [-q] [-l] [-h] [-r | -a] [header ...]

PARAMETERS

-a
    Always write .ph files, ignoring up-to-date status (mutually exclusive with -r)

-d directory
    Destination directory for output .ph files

-h
    Print help and exit

-l
    Localize: add standard #include like <sys/types.h> instead of relative paths

-q
    Quiet mode; suppress progress messages

-r
    Recursively convert entire directory trees of headers

DESCRIPTION

h2ph is a utility script distributed with Perl that automatically converts C header files (.h files) into equivalent Perl header files (.ph files). These .ph files contain Perl code representing C constants, enums, structs, typedefs, and other definitions, making it easy for Perl programs to access C library constants and types without manual effort or XS code.

The script parses #define macros into Perl constants (e.g., #define MAX_PATH 256 becomes $MAX_PATH = 256;), enums into arrays or hashes, and structs into pack templates or hashes. It handles #include directives, either recursively or by assuming standard includes.

By default, h2ph scans specified headers and places output .ph files in a Perl library directory like /usr/lib/perl5/5.38.0/$archname/auto/h2ph/, preserving the header's directory structure. Use -d to specify a custom directory. It checks timestamps to skip up-to-date files; -r forces recreation.

h2ph is invaluable for quick prototyping or simple interfaces to system libraries (e.g., socket.h, unistd.h). However, complex macros, unions, or preprocessor conditionals may require manual fixes in generated files. To use: perl h2ph /usr/include/sys/types.h, then do 'sys/types.ph'; in Perl.

CAVEATS

Does not perfectly handle complex C macros, inline functions, bitfields, or heavy #ifdef usage; generated code may need manual tweaks. Not for full C-to-Perl translation (use h2xs or c2ph for modules). Runs as Perl script, so locate via perldoc h2ph.

DEFAULT OUTPUT PATH

Files go to Perl's @INC under /auto/h2ph/ preserving .h hierarchy, e.g., sys/socket.ph.

USAGE EXAMPLE

h2ph -r -d . /usr/include/sys
Recursively converts sys headers to current directory.

In Perl: do 'sys/socket.ph'; then use $AF_INET.

HISTORY

Introduced in Perl 5.0 (1994) as part of core tools for C-Perl integration. Evolved with Perl versions; modern iterations (Perl 5.10+) add better macro handling and recursion support. Maintained in Perl's ExtUtils::h2ph module.

SEE ALSO

c2ph(1), h2xs(1), perl(1), perlxstypemap(1)

Copied to clipboard