1

我有一个包含类定义的 C++ 头文件,我想检索其成员变量的类型和名称。

像 Eclipse 和 Visual Studio 这样的编辑器这样做是为了可视化代码,所以我很感兴趣他们是否也以某些(可能是本机)脚本语言或 Java 提供 API,这将允许将成员变量类型和名称作为字符串获取,比如说,将它们写入文件。如果没有,那么也许有实用程序可以将类描述转储到一些类似 XML 的文件中?

4

1 回答 1

2

IDEs basically use a C++ compiler to extract this information because parsing C++ is hard. Even worse, the C++ compiler has to be fault-tolerant if it should work while you're writing the code.

  1. Visual Studio creates a SQL Server database in your project folder. That is the database used for code completion aka IntelliSense. Look for the file "projectname.sdf". You can write a Visual Studio add in that opens this database and accesses its members. I have done so.

    But: There is absolutely no guarantee that the information in this database is complete and correct. On small projects it will probably work ok, on large projects with several 100k LOC the database will almost certainly not be 100% complete. If you want to generate code automatically based on this database, be very, very careful.

  2. The Visual Studio compiler generates a debug symbols database that you can query after you have compiled your project. There is an example project on MSDN to do that.

  3. Clang provides an API to do that. See libclang et al.

    From that page:

    Clang provides infrastructure to write tools that need syntactic and semantic information about a program. This document will give a short introduction of the different ways to write clang tools, and their pros and cons.

    This is certainly a better option than 1) because you actually access the intermediate compiler syntax tree. Several people (e.g. Apple, Google) have written refactoring tools and syntax checkers based on Clang. More information here.

    One big caveat: Clang is currently not able to parse many Windows headers because it does not support all Microsoft compiler options.

  4. GCC can dump its syntax tree too.

于 2013-09-03T09:44:29.813 回答