initial commit
[rofl0r-makefilegen.git] / makefilegen.pl
blob5dbcd9c0e7f6e12e7b9ca7d550a448f50f1894a8
1 #!/usr/bin/env perl
2 use strict;
3 use warnings;
5 my $maindir = $ARGV[0] or die;
6 my %hdefs;
7 my @adefs;
8 my @units;
9 my %hasmain;
11 sub scandir {
12 my $dir = shift;
13 my @cfiles;
14 my @files = glob($dir . "/*");
15 for(@files) {
16 my $ext = substr($_, -2);
17 if($ext eq ".c" || $ext eq ".h") {
18 my $f;
19 my $fn = $_;
20 open($f, "<", $_);
21 while(<$f>) {
22 if((/\s*#if[n]{0,1}def ([\w_]+)/ || /\s*#if\s+\(\s+[\(]{0,1}\s*defined\s+\)\s*[\)]{0,1}\s*([\w_]+)/)) {
23 my $def = $1;
24 next if ($def =~ /_H_$/ || $def =~ /_H$/) && $def !~ /^HAVE_/;
25 if(!defined($hdefs{$def})) {
26 $hdefs{$def} = 1;
27 push @adefs, $def;
29 } elsif (/^\s*(int){0,1}(void]){0,1}\s+main\s*\(/) {
30 $hasmain{$fn} = 1;
33 close($f);
34 if($ext eq ".c") {
35 push @cfiles, $fn;
37 } elsif (-d $_) {
38 scandir($_);
41 push @units, \@cfiles if(@cfiles);
44 sub gettarget {
45 my $c = shift;
46 my @a = split /\//, $c;
47 my $x;
48 for(@a) {
49 next if $_ eq ".";
50 $x = $_;
51 last;
53 $x = "root" unless defined $x;
54 return $x;
57 scandir($maindir);
59 my $cfg;
60 open($cfg, ">", "config.mak");
61 my @adefs2 = sort {$a cmp $b} @adefs;
62 for(@adefs2) {
63 print { $cfg } "#CFLAGS+=-D" . $_ . "\n";
65 close($cfg);
67 my $h = "#Makefile autogenerated by rofl0rs makefilegen\n\n-include config.mak\n\nall: ";
68 my $f = "\n.PHONY: ";
70 my $mak;
71 my %sections;
72 my %sectionfiles;
73 open($mak, ">", "Makefile");
74 print { $mak } $h;
75 for(@units) {
76 for my $c(@$_) {
77 my $trg = gettarget($c);
78 if(!defined($sections{$trg})) {
79 $sectionfiles{$trg} = [];
80 print {$mak} $trg , " ";
81 $sections{$trg} = 1;
83 my $secaref = $sectionfiles{$trg};
84 push @$secaref, $c;
89 print { $mak } "\n\n";
90 for(keys %sectionfiles) {
91 my $allo = "";
92 my @mains;
93 my $secname = $_;
94 print { $mak } $secname, ":\n";
95 $f .= $secname . " ";
96 my $secaref = $sectionfiles{$secname};
97 for(@$secaref) {
98 push @mains, $_ if defined($hasmain{$_});
99 my $bn = substr($_, 0, -2);
100 $allo .= $bn . ".o ";
101 print { $mak } "\t" . '${CC} -c ' . $bn . '.c ${CFLAGS} -o ' . $bn . ".o\n";
103 if(@mains) {
104 for(@mains) {
105 my $bn = substr($_, 0, -2);
106 print { $mak } "\t" . '${CC} ' . $allo . ' ${CFLAGS} -o ' . $bn . ".out\n";
108 } else {
109 print { $mak } "\t" . 'ar rcs lib' . $secname . ".a " . $allo . "\n";
111 print { $mak } "\n";
113 print { $mak } $f, "\n";
114 close($mak);