Use of extern "C"

Source: Internet
Author: User

2016-12-11 22:40:48

VS Compile, you can specify to compile to C code or C + + code. C/c++-> Advanced. When you create a new CPP file, vs is likely to automatically compile the compilation from C into C + +. However, the definitions of C and C + + compiled symbols are not the same (because C + + is overloaded), so it is possible that the target file compiled with C + + will not be able to find the symbol when it calls the function in the target file that is compiled by the compiler. In order to implement the C language library for C + +, you should include the extern C declaration in the header file of the C language library, so that even if the. h file is included in a C + + file, you can still compile the. h file in the name of the language. In addition, since extern C cannot be recognized by the C compiler, all locations that use extern c should first determine whether the current compiler is using C + +.

1. IntroductionThe C + + language was originally created as "A better C", but this does not mean that C + + global variables and functions in C + + are compiled and connected in exactly the same way as C. As a language compatible with C, C + + retains some of the features of the procedural language (known as "not completely object-oriented"), so it can define global variables and functions that are not part of any class. However, after all, C + + is an object-oriented programming language, in order to support the overloading of functions, C + + to the global function of the processing method and C are obviously different. 2. speaking from the standard header fileAn enterprise once gave the following interview question: Why do standard header files have a structure similar to the following?
   #ifndef __incvxworksh    #define __incvxworksh    #ifdef __cplusplus      extern"C"  {    #endif/    *...  */    #ifdef    __cplusplus    }#endif    #endif /* __ Incvxworksh * *
Analysis Obviously, the compiler macro "#ifndef __incvxworksh, #define __incvxworksh, #endif" In the header file is to prevent the header file from being repeatedly referenced. so
#ifdef __cplusplus extern " C " {  #endif  #ifdef __cplusplus} #endif
What is the role of it? We will be in the following one by one lanes. 3. Deep Disclosure extern "C"  The extern "C"   contains a double meaning, which is literally: first, the target being modified by it is "extern", and secondly, the target it modifies is "C".  Let's take a detailed reading of this twofold meaning. The function or variable defined by extern "C" is an extern type;  extern is a keyword that indicates the scope (visibility) of functions and global variables in the C/D + + language, which tells the compiler that its declared functions and variables can be used in this module or in other modules.  Remember, the following statement: extern int A; is simply a declaration of a variable that does not define variable A and does not allocate memory space for a.  Variable A can only be defined once in all modules as a global variable, or a connection error occurs. Typically, the function and global variables that this module provides to other modules in the header file of the module are declared with the keyword extern. For example, if module B is to reference the global variables and functions defined in module A, only the header file of module A can be included.  In this way, when a function in module A is called in Module B, in the compile phase, Module B cannot find the function, but it does not error; it will find this function in the target code generated from module a during the connection phase. The keyword that corresponds to extern is static, and the global variables and functions it modifies can only be used in this module.  Therefore, a function or variable may not be modified by extern "C" only if it is used by this module.  The variables and functions modified by extern "C" are compiled and concatenated according to the C language, and the way to compile without extern "C" is to first look at how C + + is compiled for a function that is similar to c.. As an object-oriented language, C + + supports function overloading, whereas programming language C is not supported. Functions are compiled in C + + with different names in the symbol library than in the C language.  For example, suppose a function is prototyped as: void foo (int x, int y);  The function is compiled by the C compiler in the symbol library with the name _foo, while the C + + compiler produces names like _foo_int_int (different compilers may generate different names, but all use the same mechanism, and the resulting new name is called "Mangled Name"). _foo_int_int such a name includes the function name, function parameter number and type information, C + + is this mechanism to implement function overloading.  For example, in C + +, the function void foo (int x, int y) is not the same as the symbol generated by the compilation of void foo (int x, float y), which is _foo_int_float. Similarly, variables in C + + support a class in addition to local variablesmember variables and global variables. The class member variable of the program that the user writes may have the same name as the global variable, and we use the "." to differentiate.  In essence, the compiler, when compiling, is similar to the processing of the function and takes a unique name for the variable in the class, which differs from the name of the global variable named in the user program. Connection method without extern "C" declaration assuming that in C + +, the header file of module A is as follows://  module a header file Modulea.h#ifndef module_a_h#define module_a_hint foo (int x, int y  ); #endif reference the function in module B://  Module B implements the file Moduleb.cpp#include "ModuleA.h" foo (2,3);  In fact, during the connection phase, the connector looks for symbols like _foo_int_int from the target file Modulea.obj generated by module A! After adding extern "C" declaration after the compilation and connection method plus extern "C" declaration, the header file of module a becomes://  module a header file Modulea.h#ifndef module_a_h#define Module_a_hextern "c "int foo (int x, int y), #endif still calls Foo (2,3) in the implementation file of Module B, and the result is: (1) When module a compiles the target code of Foo, it does not have special handling of its name, the C language is used, and (2) the connector is in module B  The target code looks for the Foo (2,3) call, looking for the unmodified symbol name _foo.  If the function in module a declares Foo to be an extern "C" type, and Module B contains an extern int foo (int x, int y) &nbsp, then module B cannot find the function in module A, and vice versa. Therefore, it is possible to summarize the true purpose of the extern "C" statement in one sentence (the birth of any grammatical feature in any language is not arbitrary and is driven by demand from the real world.) When we're thinking about a problem, we can't just stay in the language, ask why it's doing it, what the motivation is, so we can understand a lot more in depth: Implementing a mixed programming of C + + and C and other languages. Understand the C + + in the establishment of the extern "C" motivation, we are below to specifically analyze the extern "C" the usual use of skills.      4.extern "C" the Customary method(1) in C + + references to functions and variables in C, in the C language header file (assuming cExample.h), the following processing is required: extern "C" {#include "cExample.h"} and in the C language header file,  extern "C" declarations are not supported for external functions except for extern types, and compile syntax errors occur when the. c file contains extern "C". The author of C + + reference C Function Example project contains the source code of the three files as follows:
/*C Language Header file: cExample.h*/#ifndef C_example_h#defineC_example_hextern intAddintXinty);//Note: written as extern "C" int add (int, int);#endif/*C Language Implementation file: Cexample.c*/#include"cExample.h"intAddintXinty) {returnX +y;}//C + + implementation file, call Add:cppFile.cppextern "C"{#include"cExample.h"        //Note: This is not appropriate, if this compile pass, instead, replace with extern "C" int add (int, int);}intMainintargcChar*argv[]) {Add (2,3); return 0;}
If C + + calls a. dll written in C, the extern "C" {} should be added when the header file for the. dll is included or the interface function is declared. (2) When referencing functions and variables in the C + + language, the header file of C + + must be added extern "C", but the header file that declares extern "C" cannot be directly referenced in C, only the extern "C" defined in C + + should be  The function is declared as an extern type. The author of the C-referenced function example of the three files in the project contains the following source code:
//C + + header file CppExample.h#ifndef Cpp_example_h#defineCpp_example_hextern "C" intAddintXinty);#endif//C + + implementation file CppExample.cpp#include"cppExample.h"intAddintXinty) {returnX +y;}/*C Implementation file cfile.c/* This compiles an error: #include "cExample.h"*/extern intAddintXinty);intMainintargcChar*argv[]) {Add (2,3 ); return 0;}
An in-depth understanding of the role of the extern "C" in the compile and join phases described in section 3rd will give you a real understanding of the idioms described in this section from C + + to reference C functions and C. For the example code given in section 4th, you need to pay special attention to each detail.

C + + is an object-oriented programming language, in order to support the overloading of functions, C + + to the global function of the processing mode and C are obviously different,

Question: Why do standard header files have a structure similar to the following?

#ifndef __incvxworksh

#define __incvxworksh
#ifdef __cplusplus
extern "C" {
#endif/*...*/
#ifdef __cplusplus
}
#endif
#endif/* __incvxworksh */

Analysis

Obviously, the compiler macros in the header file #ifndef __incvxworksh, #define __incvxworksh, #endif的作用是防止该头文件被重复引用. So

#ifdef __cplusplus

extern "C" {
#endif
#ifdef __cplusplus
}
#endif

What is the role of it? We will be in the following one by one lanes.

1,extern "C" contains a double meaning, literally can be obtained: first, it is modified by its target is "extern";

Second, the target that it modifies is "C". Let's take a detailed reading of this twofold meaning.

Functions or variables that are qualified by extern "C" are extern types, and extern is a keyword that indicates the scope (visibility) of functions and global variables in the C/D + + language, which tells the compiler that its declared functions and variables can be used in this module or in other modules. Remember, the following statement:

extern int A;

is simply a declaration of a variable that does not define variable A and does not allocate memory space for a. Variable A can only be defined once in all modules as a global variable, or a connection error occurs. Typically, the functions and global variables that this module provides to other modules in the header file of the module are declared with the keyword extern, for example:

If module B is to refer to the global variables and functions defined in module A, only the header file of module a can be included. In this way, when a function in module A is called in Module B, in the compile phase, Module B cannot find the function, but it does not error; it will find this function in the target code generated from module a during the connection phase .

The keyword that corresponds to extern is static, and the global variables and functions it modifies can only be used in this module. Therefore, a function or variable may not be modified by extern "C" only if it is used by this module.

The variables and functions modified by extern "C" are compiled and concatenated in C language;

2, not add the extern "C" declaration when the compilation method

Let's start with a look at how C + + is compiled for a function that is similar to.

For example, suppose a function is prototyped as:

1 void foo (int x, int y);

The function is compiled by the C compiler in the symbol library with the name _foo, and the C + + compiler will produce names like _foo_int_int (different compilers may generate different names, but all use the same mechanism, the resulting new name is called "Mangled Name"), _foo _int_int such a name includes the function name, function parameter number and type information, C + + is this mechanism to implement function overloading.

In C + +, the function void foo (int x, int y) is not the same as the symbol generated by the compilation of void foo (int x, float y), which is _foo_int_float.

Similarly, variables in C + + support class member variables and global variables in addition to local variables. The class member variable of the program that the user writes may have the same name as the global variable, and we use the "." to differentiate. In essence, the compiler, when compiling, is similar to the processing of the function and takes a unique name for the variable in the class, which differs from the name of the global variable named in the user program.

3. Connection method without extern "C" declaration

Assume that in C + +, the header file for module A is as follows:

Module a header file moduleA.h

#ifndef module_a_h
#define Module_a_h
int foo (int x, int y);
#endif

Reference the function in module B:

#include "ModuleA.h"

Foo (2,3);

In fact, during the connection phase, the connector looks for symbols like _foo_int_int from the target file Modulea.obj generated by module A!

4, add extern "C" after the declaration of the compilation and connection mode

After adding the extern "C" declaration, the header file of module a becomes:

module A header file ModuleA.h

#ifndef module_a_h
#define Module_a_h
extern "C" int foo (int x, int y);
#endif

Foo (2,3) is still called in the implementation file of Module B, and the result is:

(1) When module a compiles the target code of Foo, it does not have special handling of its name and adopts the C language method;

(2) When the connector looks for foo (2,3) call for the target code of Module B, it looks for the unmodified symbol name _foo.

If the function in module a declares Foo to be an extern "C" type, and Module B contains an extern int foo (int x, int y), module B cannot find the function in module A;

Therefore, it is possible to summarize the true purpose of the extern "C" statement in one sentence (the birth of any grammatical feature in any language is not arbitrary and is driven by demand from the real world.) When we're thinking about a problem, we can't just stay in the language, ask why it's doing it, what the motivation is, so we can understand a lot more in depth: Implementing a mixed programming of C + + and C and other languages.

5 . The customary method of extern "C"

(1) in C + +, references to functions and variables in the C language, in the case of a C language header file (assuming cExample.h), the following processing is required:

extern "C"

{
#include "cExample.h"
}

In the header file of the C language, only the extern type is specified for its external function, and the extern "C" declaration is not supported in the C language, and a compile syntax error occurs when the. c file contains the extern "C".

The author of C + + reference C function Example project contains the source code of the three files as follows:

/* C Language header file: CExample.h */

#ifndef C_example_h
#define C_example_h
extern int Add (int x,int y);
#endif
/* C language Implementation file: CEXAMPLE.C */
#include "cExample.h"
int add (int x, int y)
{
return x + y;
}

C + + implementation file, call Add:cppFile.cpp

extern "C"
{
#include "cExample.h"
}
int main (int argc, char* argv[])
{
Add (2,3);
return 0;
}

If C + + calls a. dll written in C, the header file that includes the. dll or the declaration of the interface function should be added

extern "C" {}

(2) When referencing functions and variables in the C + + language , the header file of C + + must be added extern "C", but the header file that declares extern "C" cannot be directly referenced in C, only the extern "C" defined in C + + should be The function is declared as an extern type.

The author of the C-referenced function example of the three files in the project contains the following source code:

C + + header file CppExample.h

#ifndef Cpp_example_h
#define Cpp_example_h
extern "C" int Add (int x, int y);
#endif


C + + implementation file CppExample.cpp
#include "cppExample.h"
int add (int x, int y) return x + y;
}

/* C Implementation file cfile.c

/* This compiles an error: #include "cExample.h" */
extern int Add (int x, int y);
int main (int argc, char* argv[])
{
Add (2, 3);
return 0;
}

Reference: Usage analysis of extern "C"

Use of extern "C"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.