On 12 Sep 2006 03:06:56 -0700,
pa**********@att.net wrote in
comp.lang.c++:
#include <iostream>
using namespace std;
int main()
{
extern "C" int f(int, int);
cout << f(2,3);
cin.get();
}
int f(int x, int y)
{return (x* 234);}
Using Dev C++ with Windows XP, the above code would not compile. The
error messages were: syntax error before string constant and f
undeclared.
This puzzles me somewhat as it seems quite a faithful rendering of the
extern C section of the C++ primer 4th edition.
What am I missing?
What you are missing is the fact that your prototype and your function
definition do not match. Your prototype inside main is for a file
named 'f' with C linkage, your definition after main is for a file
named 'f' with C++ linkage, because you did not put extern "C" around
the definition. These are the declarations of two different
overloaded functions with the same name.
C++ allows for a set of overloaded functions to include exactly one
with C linkage, although it can have any number with C++ linkage.
So your code in main() is trying to call a function described by the
declaration in scope at the time, not another overloaded function of
the same name.
This is no different than if you removed the extern "C" from the
declaration inside main, but changed the function definition to:
int f (double x, double y);
The call would still fail, because you are not calling the f() that
you actually defined, but a different overloaded function with the
same name, that you have not supplied.
It is correct that this use of extern C is completely redundant because
the code has no features that are unique to C or unique to C++.
However, that doesn't seem a likely reason for the compiler to
complain.
I am not sure, and I am too lazy to look up, whether C++ actually
allows two overloaded functions to have exactly the same argument list
just because one of them has C linkage. I don't think so, as the call
would be ambiguous, but I might be wrong.
The whole reason I got into this extern C business is that I wanted to
use the C facility of suspending type-checking for function parameters
using the (...) notation.
The ellipsis for functions for variable arguments lists works EXACTLY
the same in C++ as it does in C. The limitation is that you can only
pass POD (Plain Old Data) types as the variable arguments.
However, I couldn't get this to work. If someone can help me with
this, I would be grateful. C++ primer seems to imply that c++ already
supports this ellipsis notation but I didn't find it straightforward.
If what you are really trying to do is to create and call a variadic
function in C++, then post the code you can't get to work for doing
that, and ask for help.
Thank you very much for your help.
Paul Epstein
--
Jack Klein
Home:
http://JK-Technology.Com
FAQs for
comp.lang.c
http://c-faq.com/
comp.lang.c++
http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html