Welcome, guest | Sign In | My Account | Store | Cart

This script scans .c files for "#include" statements and creates a list of dependencies, suitable for inclusion in a makefile. Name this script "mkdep" and then type "mkdep *.c"; dependencies will come out standard output.

Python, 29 lines
 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
#!/usr/bin/python
 
import sys, os, re, string
 
dotExtRe = re.compile("\.[a-zA-Z]+")
includeRe = re.compile("^#[ \t]*include[ \t]*")
 
for file in sys.argv[1:]:
 
    inf = open(file)
    myIncludes = [ ]
    for x in inf.readlines():
        m = includeRe.search(x)
        if m != None:
            x = x[m.regs[0][1]:-1]
            if x[0] == '"':
                x = x[1:-1]
                if x not in myIncludes:
                    myIncludes.append(x)
    inf.close()
 
    m = dotExtRe.search(file)
    assert m != None
    dotOFile = file[:m.regs[0][0]] + ".o"
 
    sys.stdout.write(dotOFile + ": " + file)
    for x in myIncludes:
        sys.stdout.write(" " + x)
    sys.stdout.write("\n")

I needed this to help me create a Makefile.in file.

2 comments

Will Ware (author) 22 years, 8 months ago  # | flag

doesn't handle "-I<directory>" I later discovered that this doesn't handle cases where the header files must be chased down thru a string of "-I" compiler directives.Ideally this script should search include directories in the same order that the compiler will do so. I'll ponder that and see if I can figure out a fix.

Graham Dumpleton 22 years, 6 months ago  # | flag

Better off running code through cpp. You would be better of running the code files through the cpp phase of the compiler and then extracting the #line information to determine what files it is dependent on. Ie., something like:

gcc -C -E file.c | script-to-extract-dependencies

Depening on the cpp, the #line information will be output as either:

#line 1 "file.c"

or:

# 1 "file.c"

It is suggested that you not include dependencies on any files referred to using an absolute path as they tend to be system files and will make your makefile potentially non portable.

If you need -I flags, just add them as options to the compiler when running it through your script.