Insert global variable declaration with a gcc plugin

我的未来我决定 提交于 2019-12-22 08:16:12

问题


I would like to know if it's possible to insert a global variable declaration with a gcc plugin. For example if I have the following code:

test.c:

int main(void) {
  return 0;
}

and I want to transform it into:

int fake_var;

int main(void) {
  return 0;
}

Is that possible? If it's possible, in which pass and how can I do it?


回答1:


I think you'll want to take a look at varpool_add_new_variable() in varpool.c. You should be able to pass a declaration built with type VAR_DECL to it. Similarly, take a look at add_new_static_var(), but I think the former is what you want, as it was added specifically to allow declaring globals in the middle/back end.




回答2:


Ehm, no. Don't. Why would you want to? You can't use it.

The closest you can get is to define the variable in a new .c file and link it in separately, but it would still have to be declared (with extern) in test.c for test.c to use it.




回答3:


you can create a file that contains the code you want to add to the top of the input file and use the -include yourfile option.

that advises the preprocessor to assume an #include "yourfile" at the top of the input file.

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

But you have to separately build that c file since this file will be added to all compilation units.




回答4:


Using GCC -D option u can pass a value to a C program. Eg:

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

gcc -Dgvar=10 gcc.c

This may give a closest behaviour you are looking for though this is not equivalent to a global variable declaration. This is a macro substitution at compile time.




回答5:


below there is an example of create 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 it's supposed you to link after with a previous compilation you will need to declare the global var too, but you will have to declare all var with DECL_EXTERNAL(global_var) = 1 in all compilation minus the original, and only in one compilation (i.e, the original: the compilation that hold the original var ) you must only to add the propertie TREE_PUBLIC(global_var) = 1



来源:https://stackoverflow.com/questions/25998225/insert-global-variable-declaration-with-a-gcc-plugin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!