Re: extern "C" in a namespace
Okay,
here's another related one that's puzzling:
namespace N {
extern "C" void foo() {}// #1
void foo(){}// #2
}
Following that there can only be one extern "C" function of any given name,
my assumption was that this function is implicitly in the global namespace,
even if the declaration is inside a different namespace. A good compiler
would therefore warn if it encountered one in a non-global namespace. Also,
the above would in fact define a foo() at the global level (enclosed in a
misleading namespace) and one that is really inside the namespace so this
should compile and link. g++ complains about a redefinition here.
Some more tests show other strange behaviours there:
namespace N {
extern "C" void foo() {}
}
// #2
// extern "C" void foo();
// #3
// extern "C" void foo() {}
int main() {
N::foo();
// #1
// ::foo();
}
As it is, this compiles. If I remove the slashes at #1, the compiler
complains it doesn't know about such a function. If I then remove the
slashes at #2, it compiles and links(!) so it seems that the foo() is
available both as namespaced name and as global, but a former declaration
inside a given namespace is required. This is backed up by the fact that if
I remove the slashes at #3 I again get assembler errors (I consider that a
compiler bug).
Questions here are:
- Should foo() be available as namespaced function (N::foo()) at all? Should
this function therefore have two different names?
- Should the declaration of foo() in namespace N implicitly declare the
function at the global scope?
BTW: the original bug was like this:
// header
#ifdef __cplusplus
namespace N {
extern "C" {
#endif
void foo();
#ifdef __cplusplus
}
}
#endif
// implementation file, includes header
void foo() {}
This then produces different results when compiled as C and C++, but
strangely enough it still works when the header is included in a C++ TU
while the implementation file is compiled as C. It raises some portability
issues as soon as the implementation is compiled as C++ code.
Note: I'm not arguing the fact that the namespace must vanish because it
doesn't describe the interface used in the implementation file; what
puzzles me is that it works (or, rather, that it worked).
Uli
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]