-1

I have this big project that contains dozens of .c file. I want to add a global variable to each file without changing the source code. Is there anyway I can do that? Maybe with a wrapper function or in MakeFile? I appreciate any help.

Sorry didn't make it clear. What I meant was for example, I want to add a variable called int x to each file, and then I want to use a wrapper function __wrap_foo(int a, int x) to replace the original function foo(int a), while foo(int a) may or may not be used in each file. The reason I'm trying to add it as a global variable in each file is that __wrap_foo may not be the only wrapper function that want to use value int x. There might be other wrappers like __wrap_zoo(double b, int x) also uses and modifies the value of x. I hope this makes more sense.

AetX
  • 193
  • 6
  • 3
    How are the source files going to make anything useful from these global variables? – machine_1 Mar 14 '19 at 21:32
  • You can add the variable as an `extern` to a header file, and then declare it for real in one source file. – bruceg Mar 14 '19 at 21:34
  • You are unclear, what means "add a global variable" ? we can understand that in a lot of ways – bruno Mar 14 '19 at 21:38
  • What do you mean by "add a global variable to each file"? One individually named variable in each source file, i.e. different name for each file? Make one single global variable accessable in all the files? – Yunnosch Mar 14 '19 at 21:38
  • If you do not want to change the source files, which purpose are the added variables going to achieve? – Yunnosch Mar 14 '19 at 21:39
  • 1
    Your question makes no sense, you wanna add a variable but you don’t wanna use it. Then don’t add it. – Fredrik Mar 14 '19 at 21:39
  • Please provide some example code of how you are going to use those added variables. That will probably help us to understand what exactly it is what you want. – Yunnosch Mar 14 '19 at 21:40
  • Please convince us that what we are discussing here is not an XY problem. https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem – Yunnosch Mar 14 '19 at 21:41
  • Assume that you got an answer which explains how to achieve this. How are you going to test whether it actually works for you? How could you tell a working solution from a non-working one. – Yunnosch Mar 14 '19 at 21:42
  • You can use shell commands in each recipe. You can use `sed` to make changes. The fact that you are having to do this points at some larger problem with your existing code. – David C. Rankin Mar 14 '19 at 21:51

1 Answers1

0

You can force your compiler to as-if-insert an include statement at the beginning of the source file. This way, if you add -include custom.h to CFLAGS, and insert any variables, redefines, customizations to all C files that are compiled with this option.

Alex Cohn
  • 56,089
  • 9
  • 113
  • 307