I have two C++ files, say file1.cpp and file2.cpp as
//file1.cpp
#include<cstdio>
void fun(int i)
{
printf("%d\n",i);
}
//file2.cpp
void fun(double);
int main()
{
fun(5);
}
When I compile them and link them as c++ files, I get an error “undefined reference to fun(double)”.
But when I do this as C files, I don’t get error and 0 is printed instead of 5.
Please explain the reason.
Moreover I want to ask whether we need to declare a function before defining it because
I haven’t declared it in file1.cpp but no error comes in compilation.
This is most likely because of function overloading. When compiling with C, the call to
fun(double)is translated into a call to the assembly function_fun, which will be linked in at a later stage. The actual definition also has the assembly name_fun, even though it takes an int instead of a double, and the linker will merrily use this whenfun(double)is called.C++ on the other hand mangles the assembly names, so you’ll get something like
_fun@intforfun(int)and_fun@doubleforfun(double), in order for overloading to work. The linker will see these have different names and spurt out an error that it can’t find the definition forfun(double).For your second question it is always a good idea to declare function prototypes, generally done in a header, especially if the function is used in multiple files. There should be a warning option for missing prototypes in your compiler, gcc uses
-Wmissing-prototypes. Your code would be better if set up likeYou’d then not have multiple conflicting prototypes in your program.