The statement #include "file2.c"
effectively incorporates the contents of file2.c
into file1.c
. Then file1.c
is compiled as if it contains:
int function2()
{
return 2018;
}
Those lines define function2
; they tell the compiler “Here is function2
, create code for it.” Because those lines effectively appear in both file1.c
and file2.c
, your program has two copies of function2
.
Instead, you should create file2.h
that contains:
int function2();
That line tells the compiler “There exists a function called function2
, but its definition is somewhere else.”
Then, in file1.c
, use #include "file2.h"
instead of #include "file2.c"
. This will tell the compiler, while file1.c
is being compiled, what it needs to know to compile a call to function2
. The compiler will have the declaration it needs, but it will not have the definition, which is not needed in file1.c
.
Also, in file2.c
, insert #include "file2.h"
. Then file2.c
will contain both a declaration of function2
(from file2.h
) and a definition of function2
(from the actual lines in file2.c
). The purpose of this is so the compiler can see both the declaration and the definition while it is compiling file2.c
, so it can warn you if there is a typographical error that makes them incompatible.
Additionally, in C, you should use int function2(void)
rather than int function2()
. For historic reasons, the latter leaves the parameters unspecified. Using (void)
tells the compiler there are no parameters.