When my program consists of two files:
main.c
#include <stdio.h>
int main(void) {
printf("%lf\n",f());
return 0;
}
func.c
double f(int a) {
return 1;
}
compiler do not show any errors.
When my program consists of only one file:
main.c
#include <stdio.h>
int main(void) {
printf("%lf\n",f());
return 0;
}
double f(int a) {
return 1;
}
Visual C++ 2008 compiler show the following error:
Error 2 error C2371: 'f' : redefinition; different basic types d:\temp\projects\function1\function1\1.c 8 function1
Can anybody explain this strange behavior?
Your first example never uses
func.c
so I'm not sure exactly what the compiler is doing aboutf()
because it has no definition.In the second example, I don't know why you can't have two functions with different signatures, but you aren't calling the function you've defined. You call
f()
with no arguments, but thef
you define takes an int which makes it a different function.Both the programs are wrong.
Without a prototype in scope, a compiler assumes that a function returns
int
and takes an unspecified number of parameters.Let's change your files a bit:
When I compile it, gcc warns me (Visual C++ should too, in conformant mode). But let's ignore the warning.
It did not print 1, but printed 0. This is because the compiler assumed that
f()
returned anint
, and the assignmentd = f();
converted that "int
" to adouble
. The compiler still compiled the code because it couldn't tell thatf()
wasn't defined the way it was (implicitly) declared. But compiling the above program isn't required by the standard, so the compiler could have rejected it (try withgcc -Werror
for example!)If we have everything in one file:
Now the compiler sees the conflict, and gives you an error message. But, a compiler is not required to reject the above program, it may or may not.
Most compilers don't reject the first program because they don't know if you have a correct definition of the function
f()
in another translation unit or not. They reject the second program because they know that you don't.C will assume a function has the prototype int func(); unless you have told it otherwise.(Note that in C int func(); and int func(void); are different things)
In your second case, you do a call to
f()
for which the compiler hasn't seen any prototype, so it assumes it isint f();
. Later on it sees your definition forf()
which has a different prototype - and issues an error.This doesn't happen in the 1. case, as they're in different compilation units.