Insert global variable declaration with gcc plugin

I would like to know if it is possible to insert a global variable declaration using the gcc plugin. For example, if I have the following code:

test.c:

int main(void) { return 0; } 

and I want to turn it into:

 int fake_var; int main(void) { return 0; } 

Is it possible? If possible, in which passage and how can I do this?

+5
source share
5 answers

I think you need to take a look at varpool_add_new_variable () in varpool.c. You should be able to pass an ad built with type VAR_DECL. Likewise, take a look at add_new_static_var (), but I think the first is what you want, as it was added specifically to allow the declaration of global characters in the middle / end.

+2
source

The following is an example of creating a global integer var:

 //add_new_static_var, in cgraph.h tree global_var = add_new_static_var(integer_type_node); //if you want to name the var: tree name = get_identifier("my_global_name"); DECL_NAME(global_var) = name; /*AND if you have thought to use in another subsequent compilation, you will need to give it an assembler name like this*/ change_decl_assembler_name(global_var, name); 

Keep in mind that in another compilation that you were supposed to link after the previous compilation, you also need to declare a global var, but you will have to declare all var with DECL_EXTERNAL (global_var) = 1 in the entire compilation minus the original and only in one compilation (i.e. E. in the original: a compilation that contains the source var), you should only add the tree_PUBLIC (global_var) = 1 property

+1
source

Ehm, no. Not. Why do you need this? You cannot use it.

Closest you can define a variable in a new .c file and link it separately, but you still need to declare it (using extern ) in test.c for test.c to use it.

0
source

you can create a file containing the code that you want to add at the beginning of the input file and use the -include yourfile .

which advises the preprocessor to accept #include "yourfile" at the top of the input file.

see this question:
Include header files using command line option?

But you must create this c file separately, as this file will be added to all compilation units.

0
source

Using the GCC -D u option can pass a value to program C. For example:

 int main() { printf("global decl %d\n", gvar); } 

gcc -Dgvar = 10 gcc.c

This can lead to the closest behavior you are looking for, although this is not equivalent to declaring a global variable. This is macro substitution at compile time.

0
source

Source: https://habr.com/ru/post/1203225/


All Articles