aboutsummaryrefslogtreecommitdiff
path: root/makedeps
blob: 70589ca9412227c4d367520f0e93b112e0a5b172 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#!/usr/bin/env perl

use v5.12;
use warnings;
use subs qw/for_includes/;

open my $fh, ">", "deps.mk";
print $fh "# This file is generated by makedeps.\n";

while (my $f = glob("c/*.cpp")) {
	$f =~ s,^c/,,;
	$f =~ s/\.cpp$//;

	if ($f eq "main") { print $fh "b/\$(EXE):"; }
	else { print $fh "b/$f.obj:"; }

	# Print dependencies in source file.
	my @deps;
	for_includes "c/$f.cpp", sub {
		my $f = shift;
		return if grep { $_ eq $f } @deps;
		push @deps, $f;
		print $fh " c/$f";

		# Print dependencies in dependency.
		for_includes "c/$f", sub {
			my $f = shift;
			return if grep { $_ eq $f } @deps;
			push @deps, $f;
			print $fh " c/$f";
		}
	};

	print $fh "\n";
}

sub for_includes ($&) {
	my $f = shift;
	my $c = shift;
	state %cache;

	# Retrieve dependencies from cache.
	if (exists $cache{$f}) {
		$c->($_) for @{$cache{$f}};
	}

	# Find dependencies in file.
	else {
		open my $gh, "<", $f or die "($f) $!";
		while ($_ = <$gh>) {
			next if /^$/;
			last if not /#/;
			next if not /^#include\s*"([^"]+)"/;
			push @{$cache{$f}}, $1;
			$c->($1);
		}
	}
}