why not giving me "function double defined" error?

Hi,
I have the following code, I am not sure why the compiler allow it to pass, I think I have double defined the function average,i have another file which has this function average defined as well; if it is a variable, it should spit the error, isn't it? Even it is not spitting the error, why it takes the first one not the second?
Thanks for the help!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
static double average (double,double);
extern double average (double,double);

using namspace std;
int main()
{
	double x;
	double y;
	cout << "Enter value 1: ";
	while (! (cin >> x ) ) 
	{
		cout << "Bad input";
		cin.clear();
		
		while (cin.get() != '\n')
		continue;
	}
		
	cout << "Enter value 2: ";
	while (! (cin >> y ) ) 
	{
		cout << "Bad input";
		cin.clear();
		
		while (cin.get() != '\n')
		continue;
	}
	
	cout << "value = " << average(x,y) << endl;
	return 0;
}

static double average(double a, double b)
{
	//int retVal = (a + b)/2;
	return a;
}
The keyword "extern" is expecting the function from a file, and polymorphic rules of c++ make two different functions from that, since they have two different origins.
Last edited on
How would the compiler know which one to use in this case? they are essentially the same, same parameters and signature.
Since you didn't import any other library for your "extern" one, it becomes not used. If it was present in an external file, the compiler would spit back something about an ambiguous reference if they were in the same namespace.
closed account (1yR4jE8b)
The extern declaration, doesn't actually declare a function. It is simply a hint to the compiler that you will be using a function declared in another compilation unit that isn't visible at the moment, so the compiler doesn't complain. You didn't actually have a function in another compilation unit with the same signature as the one you defined here, so no ambiguity error.
Last edited on
Topic archived. No new replies allowed.