Is extern “C” required also for linking global variables used in Cpp file to the one defined in a cfile?

情到浓时终转凉″ 提交于 2019-11-28 10:42:14

问题


Is extern "C" required also for linking global variables used in Cpp file to the one defined in a c file?

It is used for linking function from C++ file which is referenced in C file because of the name mangling of function names in C++ files. Does the C compiler also changes the name of variables??


回答1:


Is extern "C" required also for linking global variables used in Cpp file to the one defined in a c file?

Portably, yes.

You might find that leaving out extern "C" works for your compiler (for example, GCC, which doesn't mangle C++ variable names in the global namespace), but that's not something you can rely on for all compilers.

Does the C compiler also changes the name of variables??

It depends on the compiler (specifically, on the ABI it uses). The language standards don't specify how language-level names map to linker symbols, so different compilers can use different name-mangling schemes.




回答2:


It is not required for variables. Extern "C" is required for functions because in C++ the functions can be defined multiple times for different number and type of parameters. Each function name includes parameters in encoded form. But the variables cannot be redefined and the names are identical (compatible) in C and C++.



来源:https://stackoverflow.com/questions/27938862/is-extern-c-required-also-for-linking-global-variables-used-in-cpp-file-to-the

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!