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.
A function declaration introduces an identifier that designates a function and, optionally, specifies the types of the function parameters (the prototype). Function declarations (unlike definitions) may appear at block scope as well as file scope.
Actually, it is not required that a function be declared before use in C. If it encounters an attempt to call a function, the compiler will assume a variable argument list and that the function returns int.
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 when fun(double)
is called.
C++ on the other hand mangles the assembly names, so you'll get something like _fun@int
for fun(int)
and _fun@double
for fun(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 for fun(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 like
// file1.hpp
#ifndef FILE1_HPP
#define FILE1_HPP
void fun(int)
#endif
// file1.c
#include "file1.hpp"
...
// file2.c
#include "file1.hpp"
int main()
{
fun(5);
}
You'd then not have multiple conflicting prototypes in your program.
This is because C++ allows you to overload functions and C does not. It is valid to have this in C++:
double fun(int i);
double fun(double i);
...
double fun(int i) { return 1;}
double fun(double i) { return 2.1; }
but not in C.
The reason you aren't able to compile it with your C++ compiler is because the C++ compiler sees the declaration as double and tries to find a definition for it. With the C compiler, you should be getting an error for this as well, I would think you didn't enter the code exactly as you said you did when testing this with the C compiler.
The main point: C++ has function overloading, C does not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With