I have the following two files:
file1.c
int main(){
foo();
return 0;
}
file2.c
void foo(){
}
Can I compile and link the two files together so the file1.c
will recognize the foo
function without adding extern
?
Updated the prototype.
gcc file1.c file2.c throws: warning: implicit declaration of function foo.
The correct way is as follows:
file1.c
file2.h
file2.c
output
It's ugly, but using gcc, you could:
-include
is a flag to the preprocessor which will include the contents of file2.c at the very top of file1.c. Having said that, it's a poor choice, and breaks down for all but the simplest of programs.You can, but you shouldn't.
Use a header file, file2.h:
Then add:
in file1.c
To compile:
As a general rule it's better (more robust) to use a header file to define the interface of each module rather than ad hoc prototypes within dependent modules. This is sometimes known as the SPOT (Single Point Of Truth) principle.
You don't need an
extern
, but file1.c must see a declaration thatfoo()
exists. Usually this declaration is in a header file.To add a forward declaration without using a header file, simply modify file1.c to: