4 use File::Basename qw(&basename &dirname);
6 # List explicitly here the variables you want Configure to
7 # generate. Metaconfig only looks for shell variables, so you
8 # have to mention them as if they were shell variables, not
9 # %Config entries. Thus you write
11 # to ensure Configure will look for $Config{startperl}.
13 # This forces PL files to create target in same directory as PL file.
14 # This is so that make depend always knows where to find PL derivatives.
16 ($file = basename($0)) =~ s/\.PL$//;
18 if ($^O eq 'VMS' or $^O eq 'os2'); # "case-forgiving"
20 open OUT,">$file" or die "Can't create $file: $!";
22 print "Extracting $file (with variable substitutions)\n";
24 # In this section, perl variables will be expanded during extraction.
25 # You can use $Config{...} to use Configure variables.
27 print OUT <<"!GROK!THIS!";
29 eval 'exec perl -S \$0 "\$@"'
33 # In the following, perl variables are not expanded during extraction.
35 print OUT <<'!NO!SUBS!';
39 h2xs - convert .h C header files to Perl extensions
43 B<h2xs> [B<-AOPXcf>] [B<-v> version] [B<-n> module_name] [B<-p> prefix] [B<-s> sub] [headerfile [extra_libraries]]
49 I<h2xs> builds a Perl extension from any C header file. The extension will
50 include functions which can be used to retrieve the value of any #define
51 statement which was in the C header.
53 The I<module_name> will be used for the name of the extension. If
54 module_name is not supplied then the name of the header file will be used,
55 with the first character capitalized.
57 If the extension might need extra libraries, they should be included
58 here. The extension Makefile.PL will take care of checking whether
59 the libraries actually exist and how they should be loaded.
60 The extra libraries should be specified in the form -lm -lposix, etc,
61 just as on the cc command line. By default, the Makefile.PL will
62 search through the library path determined by Configure. That path
63 can be augmented by including arguments of the form B<-L/another/library/path>
64 in the extra-libraries argument.
72 Omit all autoload facilities. This is the same as B<-c> but also removes the
73 S<C<require AutoLoader>> statement from the .pm file.
77 Allows a pre-existing extension directory to be overwritten.
81 Omit the autogenerated stub POD section.
85 Omit C<constant()> from the .xs file and corresponding specialised
86 C<AUTOLOAD> from the .pm file.
90 Allows an extension to be created for a header even if that header is
91 not found in /usr/include.
95 Print the usage, help and version for this h2xs and exit.
97 =item B<-n> I<module_name>
99 Specifies a name to be used for the extension, e.g., S<-n RPC::DCE>
101 =item B<-p> I<prefix>
103 Specify a prefix which should be removed from the Perl function names, e.g., S<-p sec_rgy_>
104 This sets up the XS B<PREFIX> keyword and removes the prefix from functions that are
105 autoloaded via the C<constant()> mechansim.
107 =item B<-s> I<sub1,sub2>
109 Create a perl subroutine for the specified macros rather than autoload with the constant() subroutine.
110 These macros are assumed to have a return type of B<char *>, e.g., S<-s sec_rgy_wildcard_name,sec_rgy_wildcard_sid>.
112 =item B<-v> I<version>
114 Specify a version number for this extension. This version number is added
115 to the templates. The default is 0.01.
119 Omit the XS portion. Used to generate templates for a module which is not
124 Automatically generate XSUBs basing on function declarations in the
125 header file. The package C<C::Scan> should be installed. If this
126 option is specified, the name of the header file may look like
127 C<NAME1,NAME2>. In this case NAME1 is used instead of the specified string,
128 but XSUBS are emited only for the declarations included from file NAME2.
130 Note that some types of arguments/return-values for functions may
131 result in XSUB-declarations/typemap-entries which need
132 hand-editing. Such may be objects which cannot be converted from/to a
133 pointer (like C<long long>), pointers to functions, or arrays.
137 Additional flags to specify to C preprocessor when scanning header for
138 function declarations. Should not be used without B<-x>.
145 # Default behavior, extension is Rusers
148 # Same, but extension is RUSERS
149 h2xs -n RUSERS rpcsvc/rusers
151 # Extension is rpcsvc::rusers. Still finds <rpcsvc/rusers.h>
154 # Extension is ONC::RPC. Still finds <rpcsvc/rusers.h>
155 h2xs -n ONC::RPC rpcsvc/rusers
157 # Without constant() or AUTOLOAD
158 h2xs -c rpcsvc/rusers
160 # Creates templates for an extension named RPC
163 # Extension is ONC::RPC.
166 # Makefile.PL will look for library -lrpc in
167 # additional directory /opt/net/lib
168 h2xs rpcsvc/rusers -L/opt/net/lib -lrpc
170 # Extension is DCE::rgynbase
171 # prefix "sec_rgy_" is dropped from perl function names
172 h2xs -n DCE::rgynbase -p sec_rgy_ dce/rgynbase
174 # Extension is DCE::rgynbase
175 # prefix "sec_rgy_" is dropped from perl function names
176 # subroutines are created for sec_rgy_wildcard_name and sec_rgy_wildcard_sid
177 h2xs -n DCE::rgynbase -p sec_rgy_ \
178 -s sec_rgy_wildcard_name,sec_rgy_wildcard_sid dce/rgynbase
180 # Make XS without defines in perl.h, but with function declarations
181 # visible from perl.h. Name of the extension is perl1.
182 # When scanning perl.h, define -DEXT=extern -DdEXT= -DINIT(x)=
183 # Extra backslashes below because the string is passed to shell.
184 # Note that a directory with perl header files would
185 # be added automatically to include path.
186 h2xs -xAn perl1 -F "-DEXT=extern -DdEXT= -DINIT\(x\)=" perl.h
188 # Same with function declaration in proto.h as visible from perl.h.
189 h2xs -xAn perl2 perl.h,proto.h
193 No environment variables are used.
197 Larry Wall and others
201 L<perl>, L<perlxstut>, L<ExtUtils::MakeMaker>, and L<AutoLoader>.
205 The usual warnings if it cannot read or write the files involved.
209 my( $H2XS_VERSION ) = ' $Revision: 1.16 $ ' =~ /\$Revision:\s+([^\s]+)/;
210 my $TEMPLATE_VERSION = '0.01';
216 die "h2xs [-AOPXcfh] [-v version] [-n module_name] [-p prefix] [-s subs] [headerfile [extra_libraries]]
217 version: $H2XS_VERSION
218 -f Force creation of the extension even if the C header does not exist.
219 -n Specify a name to use for the extension (recommended).
220 -c Omit the constant() function and specialised AUTOLOAD from the XS file.
221 -p Specify a prefix which should be removed from the Perl function names.
222 -s Create subroutines for specified macros.
223 -A Omit all autoloading facilities (implies -c).
224 -O Allow overwriting of a pre-existing extension directory.
225 -P Omit the stub POD section.
226 -X Omit the XS portion.
227 -v Specify a version number for this extension.
228 -x Autogenerate XSUBs using C::Scan.
229 -F Additional flags for C preprocessor (used with -x).
230 -h Display this help message
232 are any libraries that might be needed for loading the
233 extension, e.g. -lm would try to link in the math library.
238 getopts("AOPXcfhxv:n:p:s:F:") || usage;
243 $TEMPLATE_VERSION = $opt_v;
245 $opt_c = 1 if $opt_A;
246 %const_xsub = map { $_,1 } split(/,+/, $opt_s) if $opt_s;
249 $extralibs = "@ARGV";
251 usage "Must supply header file or module name\n"
252 unless ($path_h or $opt_n);
257 if( $path_h =~ s#::#/#g && $opt_n ){
258 warn "Nesting of headerfile ignored with -n\n";
260 $path_h .= ".h" unless $path_h =~ /\.h$/;
262 $path_h =~ s/,.*$// if $opt_x;
263 if ($^O eq 'VMS') { # Consider overrides of default location
264 if ($path_h !~ m![:>\[]!) {
265 my($hadsys) = ($path_h =~ s!^sys/!!i);
266 if ($ENV{'DECC$System_Include'}) { $path_h = "DECC\$System_Include:$path_h"; }
267 elsif ($ENV{'DECC$Library_Include'}) { $path_h = "DECC\$Library_Include:$path_h"; }
268 elsif ($ENV{'GNU_CC_Include'}) { $path_h = 'GNU_CC_Include:' .
269 ($hadsys ? '[vms]' : '[000000]') . $path_h; }
270 elsif ($ENV{'VAXC$Include'}) { $path_h = "VAXC\$_Include:$path_h"; }
271 else { $path_h = "Sys\$Library:$path_h"; }
274 elsif ($^O eq 'os2') {
275 $path_h = "/usr/include/$path_h"
276 if $path_h !~ m#^([a-z]:)?[./]#i and -r "/usr/include/$path_h";
279 $path_h = "/usr/include/$path_h"
280 if $path_h !~ m#^[./]# and -r "/usr/include/$path_h";
284 die "Can't find $path_h\n" if ( ! $opt_f && ! -f $path_h );
285 # Scan the header file (we should deal with nested header files)
286 # Record the names of simple #define constants into const_names
287 # Function prototypes are not (currently) processed.
288 open(CH, "<$path_h") || die "Can't open $path_h: $!\n";
290 if (/^ #[ \t]*define\s+([\$\w]+)\b\s*[^("]/) {
291 print "Matched $_ ($1)\n";
293 next if /^_.*_h_*$/i; # special case, but for what?
294 if (defined $opt_p) {
295 if (!/^$opt_p(\d)/) {
296 ++$prefix{$_} if s/^$opt_p//;
299 warn "can't remove $opt_p prefix from '$_'!\n";
306 @const_names = sort keys %const_names;
311 $module = $opt_n || do {
320 (chdir 'ext', $ext = 'ext/') if -d 'ext';
322 if( $module =~ /::/ ){
324 @modparts = split(/::/,$module);
325 $modfname = $modparts[-1];
326 $modpname = join('/',@modparts);
331 $modfname = $modpname = $module;
336 warn "Overwriting existing $ext$modpname!!!\n" if -e $modpname;
338 die "Won't overwrite existing $ext$modpname\n" if -e $modpname;
343 mkdir("$modpath$_", 0777);
347 mkdir($modpname, 0777);
348 chdir($modpname) || die "Can't chdir $ext$modpname: $!\n";
355 if( ! $opt_X ){ # use XS, unless it was disabled
356 open(XS, ">$modfname.xs") || die "Can't create $ext$modpname/$modfname.xs: $!\n";
358 require C::Scan; # Run-time directive
359 require Config; # Run-time directive
360 warn "Scanning typemaps...\n";
364 my $filename = $path_h;
365 my $addflags = $opt_F || '';
366 if ($fullpath =~ /,/) {
370 warn "Scanning $filename for functions...\n";
371 $c = new C::Scan 'filename' => $filename, 'filename_filter' => $filter,
372 'add_cppflags' => $addflags;
373 $c->set('includeDirs' => ["$Config::Config{archlib}/CORE"]);
375 $fdecls_parsed = $c->get('parsed_fdecls');
376 $fdecls = $c->get('fdecls');
380 open(PM, ">$modfname.pm") || die "Can't create $ext$modpname/$modfname.pm: $!\n";
383 warn "Writing $ext$modpname/$modfname.pm\n";
391 if( $opt_X || $opt_c || $opt_A ){
392 # we won't have our own AUTOLOAD(), so won't have $AUTOLOAD
394 use vars qw($VERSION @ISA @EXPORT);
398 # we'll have an AUTOLOAD(), and it will have $AUTOLOAD and
402 use vars qw($VERSION @ISA @EXPORT $AUTOLOAD);
411 print PM <<"END" if ! $opt_X; # use DynaLoader, unless XS was disabled
415 # require autoloader if XS is disabled.
416 # if XS is enabled, require autoloader unless autoloading is disabled.
417 if( $opt_X || (! $opt_A) ){
423 if( $opt_X || ($opt_c && ! $opt_A) ){
424 # we won't have our own AUTOLOAD(), so we'll inherit it.
425 if( ! $opt_X ) { # use DynaLoader, unless XS was disabled
428 \@ISA = qw(Exporter AutoLoader DynaLoader);
434 \@ISA = qw(Exporter AutoLoader);
439 # 1) we have our own AUTOLOAD(), so don't need to inherit it.
441 # 2) we don't want autoloading mentioned.
442 if( ! $opt_X ){ # use DynaLoader, unless XS was disabled
445 \@ISA = qw(Exporter DynaLoader);
451 \@ISA = qw(Exporter);
457 # Items to export into callers namespace by default. Note: do not export
458 # names by default without a very good reason. Use EXPORT_OK instead.
459 # Do not simply export all your public functions/methods/constants.
463 \$VERSION = '$TEMPLATE_VERSION';
467 print PM <<"END" unless $opt_c or $opt_X;
469 # This AUTOLOAD is used to 'autoload' constants from the constant()
470 # XS function. If a constant is not found then control is passed
471 # to the AUTOLOAD in AutoLoader.
474 (\$constname = \$AUTOLOAD) =~ s/.*:://;
475 my \$val = constant(\$constname, \@_ ? \$_[0] : 0);
477 if (\$! =~ /Invalid/) {
478 \$AutoLoader::AUTOLOAD = \$AUTOLOAD;
479 goto &AutoLoader::AUTOLOAD;
482 croak "Your vendor has not defined $module macro \$constname";
485 eval "sub \$AUTOLOAD { \$val }";
491 if( ! $opt_X ){ # print bootstrap, unless XS is disabled
493 bootstrap $module \$VERSION;
497 if( $opt_P ){ # if POD is disabled
506 # Preloaded methods go here.
508 # Autoload methods go after $after, and are processed by the autosplit program.
514 $author = "A. U. Thor";
515 $email = 'a.u.thor@a.galaxy.far.far.away';
519 if (@const_names and not $opt_P) {
522 =head1 Exported constants
524 @{[join "\n ", @const_names]}
528 if (defined $fdecls and @$fdecls and not $opt_P) {
531 =head1 Exported functions
533 @{[join "\n ", @$fdecls]}
538 $pod = <<"END" unless $opt_P;
539 ## Below is the stub of documentation for your module. You better edit it!
543 #$module - Perl extension for blah blah blah
552 #Stub documentation for $module was created by h2xs. It looks like the
553 #author of the extension was negligent enough to leave the stub
557 #$const_doc$fdecl_doc
569 $pod =~ s/^\#//gm unless $opt_P;
570 print PM $pod unless $opt_P;
575 if( ! $opt_X ){ # print XS, unless it is disabled
576 warn "Writing $ext$modpname/$modfname.xs\n";
592 $h =~ s#^/usr/include/##;
593 if ($^O eq 'VMS') { $h =~ s#.*vms\]#sys/# or $h =~ s#.*[:>\]]##; }
606 croak("$module::%s not implemented on this architecture", s);
619 my(@AZ, @az, @under);
621 foreach(@const_names){
622 @AZ = 'A' .. 'Z' if !@AZ && /^[A-Z]/;
623 @az = 'a' .. 'z' if !@az && /^[a-z]/;
624 @under = '_' if !@under && /^_/;
627 foreach $letter (@AZ, @az, @under) {
629 last if $letter eq 'a' && !@const_names;
631 print XS " case '$letter':\n";
633 while (substr($const_names[0],0,1) eq $letter) {
634 $name = shift(@const_names);
635 $macro = $prefix{$name} ? "$opt_p$name" : $name;
636 next if $const_xsub{$macro};
638 if (strEQ(name, "$name"))
663 $prefix = "PREFIX = $opt_p" if defined $opt_p;
664 # Now switch from C to XS by issuing the first MODULE declaration:
667 MODULE = $module PACKAGE = $module $prefix
671 foreach (sort keys %const_xsub) {
680 croak("Your vendor has not defined the $module macro $_");
689 # If a constant() function was written then output a corresponding
691 print XS <<"END" unless $opt_c;
706 my ($type, $name, $args) = @$decl;
707 return if $seen_decl{$name}++; # Need to do the same for docs as well?
709 my @argnames = map {$_->[1]} @$args;
710 my @argtypes = map { normalize_type( $_->[0] ) } @$args;
711 my @argarrays = map { $_->[4] || '' } @$args;
712 my $numargs = @$args;
713 if ($numargs and $argtypes[-1] eq '...') {
715 $argnames[-1] = '...';
718 $type = normalize_type($type);
726 for $arg (0 .. $numargs - 1) {
728 $argtypes[$arg] $argnames[$arg]$argarrays[$arg]
733 # Should be called before any actual call to normalize_type().
735 # We do not want to read ./typemap by obvios reasons.
736 my @tm = qw(../../../typemap ../../typemap ../typemap);
737 my $stdtypemap = "$Config::Config{privlib}/ExtUtils/typemap";
738 unshift @tm, $stdtypemap;
739 my $proto_re = "[" . quotemeta('\$%&*@;') . "]" ;
742 foreach $typemap (@tm) {
743 next unless -e $typemap ;
744 # skip directories, binary files etc.
745 warn " Scanning $typemap\n";
746 warn("Warning: ignoring non-text typemap file '$typemap'\n"), next
748 open(TYPEMAP, $typemap)
749 or warn ("Warning: could not open typemap file '$typemap': $!\n"), next;
750 my $mode = 'Typemap';
753 if (/^INPUT\s*$/) { $mode = 'Input'; next; }
754 elsif (/^OUTPUT\s*$/) { $mode = 'Output'; next; }
755 elsif (/^TYPEMAP\s*$/) { $mode = 'Typemap'; next; }
756 elsif ($mode eq 'Typemap') {
757 next if /^\s*($|\#)/ ;
758 if ( ($type, $image) =
759 /^\s*(.*?\S)\s+(\S+)\s*($proto_re*)\s*$/o
760 # This may reference undefined functions:
761 and not ($image eq 'T_PACKED' and $typemap eq $stdtypemap)) {
762 normalize_type($type);
766 close(TYPEMAP) or die "Cannot close $typemap: $!";
768 %std_types = %types_seen;
774 my $ignore_mods = '(?:\b(?:__const__|static|inline|__inline__)\b\s*)*';
776 $type =~ s/$ignore_mods//go;
777 $type =~ s/([\]\[()])/ \1 /g;
781 $type =~ s/\b\*/ */g;
782 $type =~ s/\*\b/* /g;
783 $type =~ s/\*\s+(?=\*)/*/g;
785 unless $type eq '...' or $type eq 'void' or $std_types{$type};
790 for $decl (@$fdecls_parsed) { print_decl(\*XS, $decl) }
797 warn "Writing $ext$modpname/typemap\n";
798 open TM, ">typemap" or die "Cannot open typemap file for write: $!";
800 for $type (keys %types_seen) {
801 print TM $type, "\t" x (6 - int((length $type)/8)), "T_PTROBJ\n"
804 close TM or die "Cannot close typemap file for write: $!";
809 warn "Writing $ext$modpname/Makefile.PL\n";
810 open(PL, ">Makefile.PL") || die "Can't create $ext$modpname/Makefile.PL: $!\n";
813 use ExtUtils::MakeMaker;
814 # See lib/ExtUtils/MakeMaker.pm for details of how to influence
815 # the contents of the Makefile that is written.
817 print PL "WriteMakefile(\n";
818 print PL " 'NAME' => '$module',\n";
819 print PL " 'VERSION_FROM' => '$modfname.pm', # finds \$VERSION\n";
820 if( ! $opt_X ){ # print C stuff, unless XS is disabled
821 print PL " 'LIBS' => ['$extralibs'], # e.g., '-lm' \n";
822 print PL " 'DEFINE' => '', # e.g., '-DHAVE_SOMETHING' \n";
823 print PL " 'INC' => '', # e.g., '-I/usr/include/other' \n";
826 close(PL) || die "Can't close $ext$modpname/Makefile.PL: $!\n";
828 warn "Writing $ext$modpname/test.pl\n";
829 open(EX, ">test.pl") || die "Can't create $ext$modpname/test.pl: $!\n";
831 # Before `make install' is performed this script should be runnable with
832 # `make test'. After `make install' it should work as `perl test.pl'
834 ######################### We start with some black magic to print on failure.
836 # Change 1..1 below to 1..last_test_to_print .
837 # (It may become useful if the test is moved to ./t subdirectory.)
839 BEGIN { $| = 1; print "1..1\n"; }
840 END {print "not ok 1\n" unless $loaded;}
849 ######################### End of black magic.
851 # Insert your test code below (better if it prints "ok 13"
852 # (correspondingly "not ok 13") depending on the success of chunk 13
856 close(EX) || die "Can't close $ext$modpname/test.pl: $!\n";
858 warn "Writing $ext$modpname/Changes\n";
859 open(EX, ">Changes") || die "Can't create $ext$modpname/Changes: $!\n";
860 print EX "Revision history for Perl extension $module.\n\n";
861 print EX "$TEMPLATE_VERSION ",scalar localtime,"\n";
862 print EX "\t- original version; created by h2xs $H2XS_VERSION\n\n";
863 close(EX) || die "Can't close $ext$modpname/Changes: $!\n";
865 warn "Writing $ext$modpname/MANIFEST\n";
866 open(MANI,'>MANIFEST') or die "Can't create MANIFEST: $!";
869 eval {opendir(D,'.');};
870 unless ($@) { @files = readdir(D); closedir(D); }
872 if (!@files) { @files = map {chomp && $_} `ls`; }
873 print MANI join("\n",@files);
877 close OUT or die "Can't close $file: $!";
878 chmod 0755, $file or die "Can't reset permissions for $file: $!\n";
879 exec("$Config{'eunicefix'} $file") if $Config{'eunicefix'} ne ':';