Search code examples
ccompilationansi-c

Why declaring a variable in a .h file will allocate memory for each .c file includes it, Is it ANSI C?


Assume I have a file.h and in it I have:

int arr[128];
(void)(*func_ptr)(int);

And I have code1.c, code2.c, code3.c includes it. Will arr and func_ptr will be global scope allocated for each .c file ? i.e. each .c file will have his own instance of arr and func_ptr? if so why is that ?

does using static can change the result ? what is the ANSI c rule?


Solution

  • Will arr and func_ptr will be global scope allocated for each .c file ?

    Yes it will, and you will end up with a linking error since you have defined the same variable names several places at global scope.

    Header files you #include in your .c files are just inserted into your .c file, there's nothing special about them. It works just as you concatenated all the header files your .c file includes, and then compile the result.

    In that respect, the net result is exactly as if you wrote int arr[128]; in each of your .c file