[cfe-dev] Parsing ObjC source file with precompiled headers in libclang

Gregory Szorc gregory.szorc at gmail.com
Sun Jan 15 22:31:10 PST 2012

On 1/15/2012 9:14 AM, Nikita Zhuk wrote:
> Hi,
> I'm parsing an ObjC source file with libclang by using Python bindings. Parsing itself works fine but since I'm parsing source files which #import framework headers such as UIKit.h and Foundation.h, the parsing is a pretty heavy operation even for the most simple main source files. I would like to use precompiled prefix headers to make the parsing faster, but apparently I'm doing something wrong. Here is the Python code I use:
> ---
> import sys
> import clang.cindex
> index = clang.cindex.Index.create()
> args = ["-include", "/Users/nzhuk/Desktop/MyTestApp/MyTestApp-Prefix.o.pch"]
> sourceFile = "/Users/nzhuk/Desktop/MyTestApp/MyTestApp/NZMasterViewController.m"
> tu = index.parse(sourceFile, args)
> if(tu == None):
> 	print "Parsing failed"
> 	sys.exit(1)
> print 'Translation unit:', tu.spelling
> for diag in tu.diagnostics:
> 	print diag
> ---
> The "MyTestApp-Prefix.o.pch" file is a precompiled header which was compiled from prefix header called "MyTestApp-Prefix.pch" with "clang -x objective-c-header [...other CC flags...] MyTestApp-Prefix.pch -o MyTestApp-Prefix.o.pch". The precompiled header is a 4.1 MB binary file which starts with characters "CPCH".
> I get the translation unit back from the parse method, but apparently the parser tries to read the PCH file as text. The diagnostics output looks like this:
> <Diagnostic severity 3, location <SourceLocation file '/Users/nzhuk/Desktop/MyTestApp/MyTestApp-Prefix.o.pch', line 1, column 1>, spelling "unknown type name 'CPCH'">
> <Diagnostic severity 3, location <SourceLocation file '/Users/nzhuk/Desktop/MyTestApp/MyTestApp-Prefix.o.pch', line 1, column 5>, spelling "expected identifier or '('">
> <Diagnostic severity 2, location <SourceLocation file '/Users/nzhuk/Desktop/MyTestApp/MyTestApp-Prefix.o.pch', line 1, column 7>, spelling 'null character ignored'>
> [ ... ]
> <Diagnostic severity 2, location <SourceLocation file '/Users/nzhuk/Desktop/MyTestApp/MyTestApp-Prefix.o.pch', line 446, column 175>, spelling 'null character ignored'>
> <Diagnostic severity 4, location <SourceLocation file None, line 0, column 0>, spelling 'too many errors emitted, stopping now'>
> I've tried replacing "-include" with "-include-pch", but that just returns a None (= null) translation unit from the parse method, without any diagnostics. Have I misunderstood the usage of precompiled headers? Any pointers would be greatly appreciated.

I /think/ you should be using Index.read() instead of Index.parse() to
load PCH files. Try:

  tu = index.read(sourceFile)

More information about the cfe-dev mailing list