[cfe-dev] How do I detect global variables?

Nico Weber nicolasweber at gmx.de
Tue Jul 22 14:18:27 PDT 2008


Hi,

to learn more about clang, I'm trying to use it to write a small  
program that parses a C program and prints all global variables it  
finds. For now, I don't want to use Sema and AST, but do that part  
myself. I've got a Preprocessor and a Parser set up, and I've derived  
a class from MinimalAction.

Now, what's the best method to find all global variable definitions?  
(global functions are not interesting, and I don't want to find  
globals form system headers).

Right now, I'm trying to overwrite ActOnDeclarator. In there, I only  
look at variables with FileContext, and reject everything that is  
`extern` (I only want the definitions of globals). Furthermore, I try  
to skip functions by checking for PQ_FunctionSpecifier, but that does  
not seem to skip all functions (for example, the `main` function of my  
test input program). And it does not skip stuff that comes from angle- 
bracket includes:

   Action::DeclTy *
   ActOnDeclarator(Scope *S, Declarator &D, DeclTy *LastInGroup) {
     // Print names of global variables
     if (D.getContext() == Declarator::FileContext) {
       IdentifierInfo *II = D.getIdentifier();
       const DeclSpec& DS = D.getDeclSpec();

       if (DS.getStorageClassSpec() != DeclSpec::SCS_extern
           && (DS.getParsedSpecifiers() &  
DeclSpec::PQ_FunctionSpecifier) == 0) {
         cerr << "Found global declarator " << II->getName()
              << " " << D.getNumTypeObjects() << endl;
       }
     }

Can you give me a few hints where I should look to add that  
functionality?

Thanks,
Nico



More information about the cfe-dev mailing list