In our project, we have pretty big C file of around 50K lines, written in 90's. I wanted to split the file based on the functionality. But, all the functions in this file are declared as static. So, file scoped. If I split the file, then the function in file1 cannot call function in file2 and vice-versa.
But, My TL feels like that there could be memory optimization by using static functions. I wrote some sample code to see if the stacks are different for different threads. It seemed like it was. Could someone please enlighten me the difference between static function and a normal one other an file scope?
3 Answers 3
In C, while defining a function, the static keyword has the following 2 major consequences :
Prevents the function name from being exported (i.e. function does NOT have external linkage). Thus, preventing linkage / direct calls from other parts of the code.
As the function is clearly marked private to the file, the compiler is in a better position to generate a complete call-graph for the function. This may result in the compiler deciding to automatically in-line the function for better performance.
Comments
All functions are implicitly declared as extern, which means they're visible across translation units. But when we use static it restricts visibility of the function to the translation unit in which it's defined. So we can say Functions that are visible only to other functions in the same file are known as static functions.
Comments
The most important difference is you cannot call the static function in any other files. i think so ,yeah?
staticis to avoid name collisions, not any optimization or efficiency concerns. So if you can add a unique enough prefix or suffix to the function names, it could be just fine to make themextern.