0

i'm trying to learn how to use pycparser and during my practice I encontured this problem. Basically I have a C file with system header like #include <stdio.h> and #include <stdlib.h> and I want to analyze it through the pycparser ast tree. I succeded in using the fake headers so i could parse the file but then i got this problem: the ast now contains a lot of typedef and doesn't contain the real headers, so after I print the ast in a file to have my c code back, it can't compile because the real headers are missing.

For example this file:

#include <stdlib.h>
#include <stdio.h>

typedef struct {
    //my struct
} NODE;

int main() {
    //do stuff

    return 0;
}

becomes this:

typedef int size_t;
typedef int __builtin_va_list;
typedef int __gnuc_va_list;
typedef int va_list;
typedef int __int8_t;
....
typedef int __uint64_t;
typedef int __int_least32_t;
typedef int __uint_least32_t;
....
typedef struct xcb_connection_t xcb_connection_t;
typedef uint32_t xcb_window_t;
typedef uint32_t xcb_visualid_t;
//a lot of typedef

typedef struct {
    //my struct
} NODE;

int main() {
    //do stuff

    return 0;
}

Doing my research i saw that #include <stdlib.h> contains the following lines:

#include "_fake_defines.h"
#include "_fake_typedefs.h"

and those headers contain all the typedef that appear in my file.

Is there a way to print back the c code with the real headers?

  • [This blog post by pycparser's author](https://eli.thegreenplace.net/2015/on-parsing-c-type-declarations-and-fake-headers) is very important – rici Jul 10 '20 at 23:36
  • I don't see how this can help me insert back the real headers – Simone Gheller Jul 11 '20 at 15:52
  • it doesn't, which is why I didn't provide an answer. But it does provide some useful explanations. I think the problem you propose is pretty challenging, particularly if you want a solution guaranteed to work in all cases. If you're willing to settle for a solution which only mostly works, delete the typedefs which come before your first line of code, and add the #include's back at that point. – rici Jul 11 '20 at 18:14

0 Answers0