您的位置:首页 > 编程语言 > C语言/C++

c与cpp的相互混合应用(c嵌入到cpp里或者cpp嵌入到c里) extern c和_cplusplus(一般在c库里合用)的来历

2013-11-29 10:11 375 查看

Linkage Directives: extern "C"
C++ programs sometimes need to call functions written in another programming language. Most often, that other language is C. Like any name, the name of a function written in another language must be declared. That declaration must specify
the return type and parameter list. The compiler checks calls to external-language functions in the same way that it handles ordinary C++ functions. However, the compiler typically must generate different code to call functions written in other languages.
C++ uses linkage directives to indicate the language used for any non-C++ function.

Declaring a Non-C++ Function
A linkage directive can have one of two forms: single or compound. Linkage directives may not appear inside a class or function definition. The linkage directive must appear on the first declaration of a function.
As an example, let's look at some of the C functions declared in the
cstdlib header. Declarations in that header might look something like
// illustrative linkage directives that might appear in the C++ header <cstring>
// single statement linkage directive
extern "C" size_t strlen(const char *);
// compound statement linkage directive
extern "C" {
int strcmp(const char*, const char*);
char *strcat(char*, const char*);
}


The first form consists of the extern keyword followed by a string literal, followed by an "ordinary" function declaration. The string literal indicates the language in which the function is written.
We can give the same linkage
to several functions at once by enclosing their declarations inside curly braces following the linkage directive. These braces serve to group the declarations to which the linkage directive applies. The braces are otherwise ignored, and the names of functions
declared within the braces are visible as if the functions were declared outside the braces.

Preprocessor Support for Linking to C——_cplusplus的来历

It
can be useful sometimes to compile the same source file in both C or C++. The preprocessor name
__cplusplus (two underscores) is automatically defined when compiling C++, so we can conditionally include code based on whether we are compiling C++.
#ifdef __cplusplus
// ok: we're compiling C++
extern "C"
#endif
int strcmp(const char*, const char*);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: