This is the mail archive of the crossgcc@sources.redhat.com mailing list for the crossgcc project.

See the CrossGCC FAQ for lots more information.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: #ifdef tool?


On Tue, 24 Jul 2001, Michael Dorin wrote:

>
>
> Anybody know of a tool that could strip unused ifdefs right from your code?
>

As has been suggested you could use gcc -E. Another alternative if
you have Solaris is a program called unifdef. You could probably
wack something together with perl that would do it as well. I think
gcc -E is your best bet since it will keep the line numbers consistent
between the source file (preprocessed text) and line numbers in the
error messages.

I've sent along something that may be a starting point. I use it
to track down unbalanced ifdefs It tells me on what line they start
and end. The code to ignore stuff in comments is probably not as
robust as it needs to be. The regex at the top of the file may be a
better way to go. I'd have to dig out my old perl notes and experiment
to remember what it does.

Hope some of this helps.

#! /usr/local/bin/perl -w

#$/ = undef;
#$_ = <>;
#s#/\*[^*]*\*+([^/*][^*]*\*+)*/|("(\\.|[^"\\])*"|'(\\.|[^'\\])*'|\n+|.[^/"'\\]*)#$2#g;
#print;

while(<>)
{

# Split on strings and delimiters.
    for (split m!("(?:\\\W|.)*?"|/\*|\*/)!)
    {
	if ($in_comment)
	{
	    #print "\n" if /\n/;
	    $in_comment = 0 if $_ eq "*/" # Look for */ if in a comment.
	}
	else
	{
	    if ($_ eq "/*")               # Look for /* if not in a comment.
	    {
		$in_comment = 1;
		#print " ";                # Comments become a space.
	    }
	    else
	    {
		&ifdef;
	    }
	}
    }

}

foreach $i (@ifdef)
{
    print "Unbalanced #if at line $i\n";
}
exit 1;

sub ifdef()
{

# put code here to ignore stuff in comments
    if ( /^#if(.?def)?/ )
    {
	push(@ifdef, $.)
    }
    if ( /#endif/ )
    {
	$ifline = pop(@ifdef);
	if ( !defined($ifline) )
	{
	    print "Unbalanced #endif at line $.\n";
	    exit(-1);
	}
	print "if --> $ifline, endif $.\n";
    }
    if ( /^#else/ )
    {
	if ( $#ifdef == -1 )
	{
	    print "#else with no #if at line $.\n";
	    exit(-1);
	}
	print "if --> $ifdef[$#ifdef], else $.\n";
    }
    close(ARGV) if (eof);
}

-- 
Joel Coltoff

I have made this letter longer than usual because I lack the time to
make it shorter. -- Blaise Pascal


------
Want more information?  See the CrossGCC FAQ, http://www.objsw.com/CrossGCC/
Want to unsubscribe? Send a note to crossgcc-unsubscribe@sourceware.cygnus.com


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]