The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.
#
# Perl script being a wrapper around the gnu ld. When a dll is specified to
#   to be built, special processing is done, else the standard ld is called.
#

# these are pretty mandatory
my $CC = '@CC@';
my $EXPORT_ALL = @EXPORT_ALL@;

# if some of extensions are undefined,
# no corresponding output will be done.
# most probably, you'd like to have an export library
# my $DEF_EXT = '@DEF_EXT@';
# my $EXP_EXT = '@EXP_EXT@';
my $LIB_EXT = '@LIB_EXT@';

#my $DEBUG ="perlld.out";
my $DEBUG =undef;

my $args = join(" ",@ARGV); # get args
my $verbose =grep(/^\-(v|\-verbose)$/, @ARGV);

sub shellexec;

if ($DEBUG) {
  open DEBUGFILE, ">>$DEBUG";
  print DEBUGFILE "\n--- " .localtime() ."\nargs:\n$args\n\nenvironment:\n";
  foreach (keys(%ENV)) { print DEBUGFILE $_, "=", $ENV{$_}, "\n"; };
}

if ($args !~ /\-o (\S+)/) {
  print DEBUGFILE "+ no dll output -- passing to gcc\n\n" if $DEBUG;
  shellexec("$CC $args\n");
} else {
  my ($path, $command, $dllname, $libname) ='';

  $dllname =$1;
  print DEBUGFILE "output file: $dllname\n" if $DEBUG;
  # remove -o from args
  $args =~ s/(^| )\-o \S+/$1/;

  # Check for path:
  if( $dllname =~ /.*[\/\\]/){
    $dllname = $';
    $path = $&;
    $path =~ s,[/\\](\.[/\\])*,/,g;
  }
  if ($dllname =~ /\./) { $libname =$`; } else { $libname =$dllname; };
  my $v_e_r_s = '@VERSION@';
  $v_e_r_s =~ tr/./_/;
  if ( $dllname =~ /libperl.*/) { 
    $dllname ="cygperl$v_e_r_s.dll";
  } else {
  $dllname ="$libname.dll";
  }
  $libname ="lib$libname" unless ($libname =~ /^lib/);
  print DEBUGFILE "dll name: $dllname\nimport library: $libname\npath: $path\n" if $DEBUG;

  $command ="$CC -shared -o  $dllname";
#  $command .=" --verbose" if $verbose;

  $command .=" -Wl,--output-def=$libname$DEF_EXT" if $DEF_EXT;
  $command .=" -Wl,--output-exp=$libname$EXP_EXT" if $EXP_EXT;
  $command .=" -Wl,--out-implib=$libname.dll$LIB_EXT" if $LIB_EXT;
  $command .=" -Wl,--export-all-symbols" if $EXPORT_ALL;
  $command .=" -Wl,--enable-auto-import -Wl,--stack,8388608"; # always

  # other args are passed through
  shellexec("$command \\\n$args\n");

  if ($path) {
    $command ="mv $dllname";
    $command .=" $libname.dll$LIB_EXT" if $LIB_EXT;
    shellexec("$command $path\n");
  };
};
close DEBUGFILE if $DEBUG;

#---------------------------------------------------------------------------
sub shellexec{
  my $command =shift;
  print $command;
  print DEBUGFILE $command if $DEBUG;
  system($command) == 0
    or die "perlld: *** system() failed to execute\n$command\n";
};

1;