All functions are global by default: we cannot define the same function twice in two different files so I assume they are in the same namespace.
If i compile the following code with gcc -Wall main.c dep.c -o test", it runs giving me the output I have been called but triggering a compilation warning implicit declaration of function ‘dummy’.
However, I could call the function dummy coming from another file without using a header. Couldn’t we just do it for everything? Why do we need headers?
# main.c
int main() {
dummy();
return 0;
}
# dep.c
#include <stdio.h>
void dummy() {
printf("I have been called\n");
}
EDIT: About the duplicate, I saw this question before asking mine and I don’t think they are the same. What surprised me and is not present in the duplicate question is that I could execute the function even if I did not defined it before.
>Solution :
All functions are global by default: we cannot define the same function twice in two different files so I assume they are in the same namespace.
That is not what global means, nor is that a namespace issue. It is a scope issue, as well as linkage. Functions in C have file scope, not global scope.
If a language has a true global scope, then a name declared once would be known throughout a program. Neither C nor C++ has this, aside from things built into the language such as keywords (and not even library functions).
C has file scope, as well as lesser scopes. In file scope, a name declared outside of any function is known from its declaration to the end of the translation unit (the source file being compiled, including, recursively, any files it includes). To make the name known in another translation unit, there must be a declaration in that translation unit. This is most often done by putting a declaration in a header file and including that header file in multiple source files, but each compilation processes it as a separate declaration. So this is not global scope.
Once names are declared at file scope and translation units are compiled, the names can be made to refer to the same object or function via linkage. There is a separate link step after compilation that does this.
It is possible to write software that scans source files for declarations and constructs a header that publishes those declarations, so that a single declaration will be known to all source files that include that header file. However, this would be an addition to the build process outside of the C and C++ standards.
… a compilation warning implicit declaration of function ‘dummy’.
However, I could call the function dummy coming from another file without using a header.
This is a legacy behavior stemming from ancient C. You should avoid using it. It will not provide correct declarations for most functions, and, because of that, it is error prone.