Art Gillespie

October 27, 2009 at 1:21pm
home

C++ Include Guard User Script for Xcode

I get sick of typing in the C++ header guards every time I create a new class in Xcode, so I wrote this user script to automatically generate them. To use it, create a new user script (I called mine ‘CPP include guards’) in Xcode and paste in the following code. A caveat: I’ve only tested this in Xcode 3.2.1 on Snow Leopard.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#!/usr/bin/env python

import os

path = "%%%{PBXFilePath}%%%"

if not os.path.exists(path) or not os.path.isfile(path):
    # the path can be gibberish, according to XCode docs,
    # so make sure it both exists and is a file. If not,
    # no output
    exit()

filename = os.path.split("%%%{PBXFilePath}%%%")[1]

guard = "__%s__" % (filename.upper().replace(".", "_"),)

print "#ifndef %s" % (guard,)
print "#define %s" % (guard,)
# set the insert point between the guards
print "%%%{PBXSelection}%%%"
print "#endif // %s" % (guard,)