获取C语言数据类型大小

December 28th, 2009 by 王 聪 Leave a reply »

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

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

PERL:
  1. #!/usr/bin/perl -w
  2.  
  3. use strict;
  4. use File::Temp qw/tempfile tempdir/;
  5.  
  6. die "Wrong usage.\n" unless @ARGV == 1;
  7. my $type=$ARGV[0];
  8. my $dir = tempdir(CLEANUP => 1);
  9. my ($obj, $src) = tempfile("$dir/XXXXX", SUFFIX => '.c', UNLINK => 0);
  10. open my $fd, ">$src" or die "can't create file: $!";
  11. $src =~ s/\.c$//g;
  12. my $exe_file = $src;
  13.  
  14. print $fd <<EOF;
  15. #include <stdio.h>
  16. #include <stdlib.h>
  17. #include <stddef.h>
  18. #include <stdbool.h>
  19. #include <unistd.h>
  20. #include <dirent.h>
  21. #include <sys/types.h>
  22. #include <sys/socket.h>
  23. #include <netinet/in.h>
  24. #include <sys/stat.h>
  25. #include <sys/time.h>
  26. #include <regex.h>
  27. #include <obstack.h>
  28. int
  29. main (void)
  30. {
  31.   $type x;
  32.   printf ("%d\\n", sizeof x);
  33.   exit (0);
  34. }
  35. EOF
  36. my $result = qx(gcc -o $exe_file $exe_file.c && $exe_file);
  37. print $result;

根据贵国法律法规和政策,部分文章内容未予显示。 powered by 滤霸

2 comments

  1. Kermit Mei says:

    前几天也想写个这东西,不过没你这么绝,用perl生成源代码再编译……这个方法很灵活,但是有个问题,如果要求的数据结构不再你的代码头文件中,不是算不了吗?所以要加个参数指定struct所在的头文件就更灵活了。

    [Reply]

    王 聪 reply on January 9, 2010 9:50 pm:

    恩,如果你需要可以自己加上这个功能。

    [Reply]

Leave a Reply

葡驻京办ICP备07006283号