Comment and Line counting in C

This is an Awk script that I wrote in 5/93, with the goal of counting lines of code and comments in a large C/C++ project I was working on. It produces three numbers: The number of code lines, the number of comments (note that multiline comments are counted as one!) and the number of raw lines, per file and overall. It also reports the percentage of comments, ie (comments / raw lines) * 100.
For example, here is the output for the Linux kernel source, version 2.2.16:
                                                          
----------File---Code---Comments---Raw Lines------------------------------------
         sys.c    716        193        1025
       panic.c     59         21          90
      itimer.c    133         21         173
      printk.c    365        101         487
       ksyms.c    343         49         426
       sched.c   1262        581        2081
        kmod.c    101         56         187
 exec_domain.c     92         20         128
    resource.c    130         42         189
  capability.c    142         40         216
        fork.c    547        126         763
         dma.c     66         39         128
      module.c    767        118        1020
        info.c     22          6          38
     softirq.c     36         26          70
      signal.c    776        177        1099
        acct.c    201        133         363
        time.c    238        166         423
      sysctl.c    997        115        1190
        exit.c    394         95         540
--------------------------------------------------------------------------------
 Total code: 7387
 Total comments: 2125
 Total raw lines: 10636
Comment percentage: 22.340202

Source code is at this link. To run it, I use 'awk -f lc.awk *.c'. Enjoy!

Note that the SLOCcount project is a much more deluxe resource - you might want to check it out. URL is http://www.dwheeler.com/sloccount/
There is, of course, a debian package for it.

Navigation Links

  • Back to code page
  • Back to home page