[cfe-dev] clang Find the last #include

mats petersson via cfe-dev cfe-dev at lists.llvm.org
Fri Dec 8 02:45:00 PST 2017


Note that this sort of problem needs to be solved in a "context-aware" way.
Assuming your "extrainclude.h" contains something that you want to stick
into the global context of the file, it needs to cope with:

#include <stdio.h>
...
void func()
{
#define SOME_MACRO ...
#include "myheader.h"
... // more code here ...
}

You most likely don't want to insert your header after the inclusion of
"myheader.h" in this case. Likewise, if you want to for example wrap malloc
& free with macros for debugging [or some other functions], you will need
to avoid this:

#include <stdio.h>
...
int main()
{
...
}

#include "mytable.h"

Another interesting scenario is if you have #if along with your includes;

#include <stdio.h>
...
#if WINDOWS
#include "some_windows_file.h"
#else
#include "some_linux_file.h"
#endif

You don't want to insert your header file after only the linux include... :)

Maybe not a very common style of programming, but it does happen that some
header files are included "last" in a file.

I know that I've not told you how to solve the problem, but if you want to
solve this for generic cases, you will need to consider these things as
well as "which is the last of the includes".

For the simple case, a small script in awk, python or something similar is
probably all you actually need - but for the more complex cases, you need a
whole lot more logic, and actually understand "where you are" in the
source-file.

--
Mats

On 8 December 2017 at 09:24, 于 秋沣 via cfe-dev <cfe-dev at lists.llvm.org>
wrote:

> Hi All,
>
> I'm working on a project which given a C/C++ source code, I need to find
> the last #include and insert one additional #include right after that. For
> example, suppose I have a file called Test.c which looks like this:
>
> #include <stdio.h>
> #include <stdlib.h>
> int main(){
>     // some code here...
> }
>
> I want to get the location of the #include <stdlib.h> and insert one extra
> #include, then the code should be like this:
>
> #include <stdio.h>
> #include <stdlib.h>
> #include "extraInclude.h"
> int main(){
>     // some code here....
> }
>
> I feel like the right class I need to use is clang::Preprocessor and
> clang::PPCallbacks, but I haven't figured out a way to implement this.
>
> Any help would be appreciated.
>
> Patrick
>
>
> _______________________________________________
> cfe-dev mailing list
> cfe-dev at lists.llvm.org
> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-dev
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20171208/12d81baa/attachment.html>


More information about the cfe-dev mailing list