且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当为extern&QUOT使用; C"在简单的话?

更新时间:2023-02-15 21:02:37

您需要使用的externC声明编译已实现的函数/时在C ++中C.使用的externC告诉编译器/连接器使用C命名和调用约定,而不是C ++名称重整和C ++调用约定将用于除此以外。对于其他图书馆提供的功能,你几乎永远不会需要使用的externC,以及编写库就已经有这个在那里,它出口的公共API这两个C和C ++。但是,如果你写的你想无论是在C和C ++中提供一个图书馆,那么你将不得不把有条件地在你的头。

You need to use extern "C" in C++ when declaring a function that was implemented/compiled in C. The use of extern "C" tells the compiler/linker to use the C naming and calling conventions, instead of the C++ name mangling and C++ calling conventions that would be used otherwise. For functions provided by other libraries, you will almost never need to use extern "C", as well-written libraries will already have this in there for the public APIs that it exports to both C and C++. If, however, you write a library that you want to make available both in C and in C++, then you will have to conditionally put that in your headers.

对于所有的C code是C ++ code ......不,这是不正确的。这是一个流行的神话,C ++是一个C的超集。虽然C ++肯定力争用C尽可能兼容的,也有一些不兼容性的。例如,布尔是有效的C ++,但不是有效的C,而 _Bool 的存在于C99,而不是用在C ++中。

As for whether all C code is C++ code... no, that is not correct. It is a popular myth that C++ is a "superset of C". While C++ certainly strives to be as compatible with C as possible, there are some incompatibilities. For example, bool is valid C++ but not valid C, while _Bool exists in C99, but is not available in C++.

至于是否会永远需要使用externC与系统的.H文件....任何精心设计的实施将有那些在那里等你,这样你就不需要使用它们。不过,可以肯定,提供他们,你应该包括以C开头,并且省略.H相当于头文件。例如,如果包括<文件ctype.h>中几乎任何合理的制度将有外部的C加入;但是,为了保证一个C ++ - 兼容的头,您应该包含头< cctype>

As to whether you will ever need to use extern "C" with the system's ".h" files.... any well-designed implementation will have those in there for you, so that you do not need to use them. However, to be certain that they are provided, you should include the equivalent header file that begins with "c" and omits ".h". For example, if you include <ctype.h>, almost any reasonable system will have the extern "C" added; however, to be assured a C++-compatible header, you should instead include the header <cctype>.

您还可能有兴趣在从C ++ FAQ精简版

You may also be interested in Mixing C and C++ from the C++ FAQ Lite.