I have been reading a book about compiler and linker.The book give a demo about use the extern "C" to test the name mangling:
#include <stdio.h>
namespace myname{
int var = 42;
}
extern "C" double _ZN6myname3varE;
int main(){
printf("%d\n", _ZN6myname3varE);
return 0;
}
The book tells that it will print 42 but I gets an error when compile it. I use:
g++ test_extern_c.cpp -o test_extern_c
and get:
test_extern_c.cpp:15:19: error: type mismatch with previous external decl of ‘double _ZN6myname3varE’ [-fpermissive]
extern "C" double _ZN6myname3varE;
^
test_extern_c.cpp:12:9: note: previous external decl of ‘int myname::var’
int var = 42;
^
test_extern_c.cpp:15:19: error: redeclaration of ‘double _ZN6myname3varE’
extern "C" double _ZN6myname3varE;
^
test_extern_c.cpp:12:9: note: previous declaration ‘int myname::var’
int var = 42;
So i wonder what happen.And I also change the type of the _ZN6myname3varE to int.And it will give the compiler error:
test_extern_c.cpp:15:16: error: redeclaration of ‘int _ZN6myname3varE’
extern "C" int _ZN6myname3varE;
^
test_extern_c.cpp:12:9: note: previous declaration ‘int myname::var’
int var = 42;
Is something different between my environment and the book's? Or may be the different version of g++ have different rule?
I have make some explorer:
- delete the code
extern "C" double _ZN6myname3varE;
and it can be compiled and the result is 42. move the code
extern "C" double _ZN6myname3varE;
to the top of namespace and change the type:#include <stdio.h> extern "C" int _ZN6myname3varE; namespace myname{ int var = 42; } //extern double _ZN6myname3varE; int main(){ printf("%d\n", _ZN6myname3varE); return 0; }
and the result is 42 also.