Deep Exploration of the meaning of extern "C" in C ++

Source: Internet
Author: User
Deep Exploration of the meaning of extern "C" in C ++
1. Introduction
C ++ was originally created as "a better C", but this does not mean that C ++ has global variables similar to C.
And functions are compiled and linked in the same way as C. As a language compatible with C, C ++ retains
A part of Procedural language features, so it can define global variables and functions that do not belong to any class. However, after all, C ++
It is an object-oriented programming language. To support function overloading, C ++ has a clear understanding of how to handle global functions and C
.
2. Start with the standard header file
An enterprise once gave the following interview questions:
Interview Questions
Why do standard header files have a structure similar to the following?
# Ifndef _ test_h
# DEFINE _ test_h
# Ifdef _ cplusplus
Extern "C "{
# Endif
/*...*/
# Ifdef _ cplusplus
}
# Endif
# Endif/* _ test_h */
Analysis
Obviously, the compilation macro "# ifndef _ test_h, # DEFINE _ test_h, # endif" in the header file is used to prevent
This header file is repeatedly referenced.
So
# Ifdef _ cplusplus
Extern "C "{
# Endif
# Ifdef _ cplusplus
}
# Endif
What is the role?
3. Deep encryption extern "C"
Extern "C" contains a double meaning, which can be obtained literally: first, the target to be modified is "extern;
Secondly, the target to be modified is "C. Let's explain these two meanings in detail.
The function or variable specified by extern "C" is of the extern type;
Extern is a keyword in C/C ++ that indicates the range (visibility) of functions and global variables.
V. The Compiler. The declared functions and variables can be used in this module or other modules. Remember, the following statements:
Extern int;
It is just a declaration of a variable. It does not define variable a and does not allocate memory space for variable a (note:
Generally, the compiler will declare the preceding statement.
Variable definition, which is automatically defined when the variable declaration is first encountered ). Variable a acts
A global variable can only be defined once. Otherwise, a connection error occurs.
In general, the function and global variables referenced by this module to other modules are provided in the module header file with keywords.
Extern declaration. For example, if Module B wants to reference the global variables and functions defined in module A, it only needs to include module
. In this way, when Module B calls A function in module A, Module B cannot find this function in the compilation phase.
Function, but no error is reported. It will find this function in the target Code Compiled by module A in the connection phase.
The keyword corresponding to extern is static. The global variables and functions modified by it can only be used in this module. Because
Therefore, a function or variable can only be used by this module, and cannot be modified by extern "C.
Variables and functions modified by extern "C" are compiled and connected in the C language;
Compilation Method without the extern "C" declaration
First, let's take a look at how C-like functions are compiled in C ++.
As an object-oriented language, C ++ supports function overloading, while Procedural Language C does not. Function compiled by C ++
The name in the symbol library is different from that in the C language. For example, assume that the prototype of a function is:
Void foo (int x, int y );
After the function is compiled by the C compiler, its name in the symbol library is _ foo, while the C ++ compiler will generate an image
_ Foo_int_int (different compilers may generate different names, but they all adopt the same mechanism,
The new name is called "mangled name ").
A name such as _ foo_int_int contains the function name, number of function parameters, and type information. C ++ relies on this mechanism.
To implement function overloading. For example, in C ++, void foo (int x, int y) and void foo (int x, float
Y) The symbols generated by the compilation are different, and the latter is _ foo_int_float.
Similarly, variables in C ++ support both local variables and class member variables and global variables. The
Class member variables may have the same name as global variables, which are differentiated. In essence, when the compiler is compiling
Number processing is similar, and a unique name is also used for the variables in the class.
The name of the local variable is different.
Connection method when extern "C" is not added
Suppose in C ++, the header file of 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 this function in Module B:
// Module B implements the file moduleB. cpp
# I nclude "moduleA. h"
Foo (2, 3 );
In fact, in the connection phase, the connector will find the target file moduleA. obj generated by module.
_ Foo_int_int!
Compilation and Connection Methods After the extern "C" clause is added
After the extern "C" statement is added, the header file of module A is changed:
// Module A header file moduleA. h
# Ifndef MODULE_A_H
# Define MODULE_A_H
Extern "C" int foo (int x, int y );
# Endif
In Module B's implementation file, foo (2, 3) is still called. The result is:
(1) When module A compiles the foo target code, it does not perform special processing on its name.
Method;
(2) When the connector looks for the 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 that foo is of the extern "C" type, and Module B contains the extern int
Foo (int x, int y), Module B cannot find the function in module A, and vice versa.
Therefore, we can use a single sentence to summarize the true purpose of the extern "C" Statement (any syntax feature in any language
The birth of nature is not random, but driven by the needs of the real world. When thinking about the problem, we can't just stay
In this case, we need to ask why the language is used and what is its motivation.
):
Realize mixed programming of C ++, C and other languages.
Understand the motivation for setting up extern "C" in C ++. Next we will analyze the common usage skills of extern "C.
4. Usage of extern "C"
(1) reference the functions and variables in C language in C ++ and include the header file of C language (for example, cExample. h)
The following operations are required:
Extern "C"
{
# I nclude "cExample. h"
}
In the header file of the C language, the external function can only be specified as the extern type, and the extern type is not supported in the C language.
"C" Declaration, when the. c file contains extern "C", a compilation syntax error occurs.
The source code of the three files in the example project of C ++ referenced by the author is as follows:
/* C header file: cExample. h */
# Ifndef C_EXAMPLE_H
# Define C_EXAMPLE_H
Extern int add (int x, int y );
# Endif
/* C implementation file: cExample. c */
# I nclude "cExample. h"
Int add (int x, int y)
{
Return x + y;
}
// C ++ implementation file, call add: cppFile. cpp
Extern "C"
{
# I nclude "cExample. h"
}
Int main (int argc, char * argv [])
{
Add (2, 3 );
Return 0;
}
If C ++ calls a. DLL file written in C language, when it includes a. DLL header file or declares an interface function
Extern "C "{}.
(2) When referencing functions and variables in C ++ in C, the header file of C ++ needs to add extern "C",
The header file that declares extern "C" cannot be directly referenced in the language. Only the extern defined in C ++ should be referenced
The "C" function is declared as the extern type.
The source code of the three files contained in the example project of C ++ is as follows:
// 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
# I nclude "cppExample. h"
Int add (int x, int y)
{
Return X + Y;
}
/* C implementation file cfile. c
/* Compilation errors: # I nclude "cexample. H "*/
Extern int add (int x, int y );
Int main (INT argc, char * argv [])
{
Add (2, 3 );
Return 0;
}
If you thoroughly understand the role of extern "C" described in section 3rd in the compilation and connection phases, you can truly
Understand the usage of referencing c Functions and C ++ functions from C ++ described in this section. For the sample code given in section 4th,
Pay special attention to the details.

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.