获取C语言数据类型大小

一个简单的脚本,可以在命令行下获取C语言中数据类型的大小。在邮件列表的讨论中看到的这个主意,我用 Perl 重写了一下。

代码很简单,见下。分享一下,希望对你有用。
[perl]

!/usr/bin/perl -w

use strict;
use File::Temp qw/tempfile tempdir/;

die “Wrong usage.n” unless @ARGV == 1;
my $type=$ARGV[0];
my $dir = tempdir(CLEANUP => 1);
my ($obj, $src) = tempfile(“$dir/XXXXX”, SUFFIX => ‘.c’, UNLINK => 0);
open my $fd, “>$src” or die “can’t create file: $!”;
$src =~ s/.c$//g;
my $exe_file = $src;

print $fd <<eof;

include

include

include

include

include

include

include

include

include

include

include

include

include

int
main (void)
{
$type x;
printf (“%d\n”, sizeof x);
exit (0);
}
EOF
my $result = qx(gcc -o $exe_file $exe_file.c && $exe_file);
print $result;
[/perl]