开发者

extern "C" (C linkage) by default

开发者 https://www.devze.com 2023-01-18 23:39 出处:网络
Question Do GCC, MSVC, or Clang, or some combination support setting linkage to default to C? Background

Question

Do GCC, MSVC, or Clang, or some combination support setting linkage to default to C?

Background

I have a large mixed C/C++ project, and while it's easy and logical to export symbols in the C++ sources开发者_开发技巧 with C linkage, those same sources are assuming the stuff in the rest of the project are under C++ linkage.

The current situation requires me to explicitly wrap anything the C sources use that is defined in the C++ sources and everything the C++ sources use from the C sources with extern "C++".

To top things off, I can't put extern "C" around entire source or header files, as the actual C++ stuff will then complain. (Such as from #include <memory> or templates I've defined.)


The standard pattern in a header file is:

#ifdef __cplusplus

// C++ stuff

extern "C" {
#endif

// C/C++ stuff

#ifdef __cplusplus
}
#endif

I'm not sure you've got any other options. The C/C++ stuff must be declared with C linkage everywhere. The C++-specific stuff must be declared with C++ linkage everywhere.


"C" linkage by default makes only sense for C sources, not for C++ sources, and vice versa. "C" linkage usually implies that names/symbols will not be mangled. "C" linkage is not expressive enough to be usable for C++ sources, e.g. for overloaded functions.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号