5

Is it possible that a function in ANSI C cannot be accessed from some other file? How and when functions have limited access? At first I thought that if a function is not included in any header it's private. But it doesn't seem to be the case.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
avivgood2
  • 227
  • 3
  • 19
  • When functions are `static` their scope is that compilation unit. Strict C requires a function declaration or a definition to be visible before the function is called, but a compiler might be permissive, and the function found by the linker. The type and argument assumptions must match. – Weather Vane Mar 30 '20 at 14:00
  • There is nothing magical about header files. The `#include` directive just inserts the text of the file being included into the compilation unit at translation phase 4. The compiler does not know anything about functions until translation phase 7. Header files are a good way to share common declarations between different .c files. – Ian Abbott Mar 30 '20 at 14:50

1 Answers1

11

Are all functions in c global?

No. For one thing, what many call (sloppily) global, the C Language calls file scope with external linkage.

Also, even in a translation unit (a fancy way to say "preprocessed C file"), a function identifier is only visible (in scope) from its declaration to the end of the translation unit (or even the enclosing block).

To give a function identifier internal linkage (so another function or object of the same name can exist in a different object file) you use the static keyword.

Jens
  • 69,818
  • 15
  • 125
  • 179