How C ++ programmers explain the role of extern & quot; C & quot; to a java Engineer

Source: Internet
Author: User

How C ++ programmers explain the role of extern "C" to a java Engineer

Today, I am working on Android development. What is external "C?
I said: To enable C ++ to compile classes or functions programmed in C language.

I guess he doesn't understand what I mean. Maybe I can't explain what this is.

Introduction
C ++ retains the features of some procedural languages, so it can define global variables and functions that do not belong to any class. However, C ++ is an object-oriented programming language after all. To support function overloading, C ++ treats global functions differently from C.
The main function of extern "C" is to call other C code correctly. After the extern "C" is added, it indicates that the code of the compiler is compiled in C language instead of C ++. C ++ supports function overloading. Therefore, during function compilation, the parameter types of the function are added to the compiled code, not just the function name; C language does not support function overloading. Therefore, when compiling a function in C language code, the parameter type of the function is not included. Generally, the function name is included.
For example, if you have developed a DLL library using C, in order to enable the C ++ language to call your DLL output (Export) function, you need to use extern "C" to force the compiler not to modify your function name.

Reveal the extern "C"
Starting from the standard header file

# Ifndef _ INCvxWorksh/* prevents this header file from being repeatedly referenced */# define _ INCvxWorksh # ifdef _ cplusplus/_ cplusplus is a custom macro extern "C "{// tell the compiler, this part of the code is compiled in the C language format, instead of C ++ # endif/***** some declaration or so *****/# ifdef _ cplusplus} # endif/* _ INCvxWorksh */

Meaning of extern "C"
Extern "C" contains a double meaning, which can be obtained literally: first, the target is "extern", and second, the target is "C.
The function or variable specified by extern "C" is of the extern type;
1. extern keyword
Extern is a keyword in C/C ++ that indicates the range (visibility) of functions and global variables. This keyword tells the compiler, the declared functions and variables can be used in this module or other modules.
In general, the function and global variables referenced by this module to other modules are declared with the keyword extern in the module header file. For example, if Module B wants to reference the global variables and functions defined in module A, it only needs to include the header file of module. In this way, when Module B calls A function in module A, although Module B cannot find the function in the compilation phase, no error is reported; it will find this function from the target Code Compiled by module A in the Link phase.
The keyword corresponding to extern is static. The global variables and functions modified by it can only be used in this module. Therefore, a function or variable can only be used by this module and cannot be modified by extern "C.

2. Variables and functions modified by extern "C" are compiled and linked in C language.
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. The name of the function in the symbol library after being compiled by C ++ 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 generates names such as _ foo_int_int (different compilers may generate different names, but all adopt the same mechanism, and 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 ++, the void foo (int x, int y) and void foo (int x, float y) functions generate different symbols, 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 of the program written by the user may have the same name as the global variables. We will distinguish them. In essence, the compiler uses a unique name for the variables in the class when compiling, similar to the function processing. This name is different from the global variable name with the same name in the user program.

If C ++ calls a. DLL written in C language, when it includes the header file of. DLL or the declared interface function, it should add extern "C "{}.

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!
Extern "C" makes a function-name in C ++ have 'C' linkage (compiler does not mangle the name) so that client C code can link to (I. e use) your function using a 'C' compatible header file that contains just the declaration of your function. your function definition is contained in a binary format (that was compiled by your C ++ compiler) that the client 'C' linker will then link to using the 'C' name.

Since C ++ has overloading of function names and C does not, the C ++ compiler cannot just use the function name as a unique id to link, so it mangles the name by adding information about the arguments. a c compiler does not need to mangle the name since you can not overload function names in C. when you state that a function has extern "C" linkage in C ++, the C ++ compiler does not add argument/parameter type information to the name used for linkage.

Just so you know, you can specify "C" linkage to each individual declaration/definition explicitly or use a block to group a sequence of declarations/definitions to have a certain linkage:

extern "C" void foo(int);extern "C"{   void g(char);   int i;}

If you care about the technicalities, they are listed in section 7.5 of the C ++ 03 standard, here is a brief summary (with emphasis on extern "C "):

Extern "C" is a linkage-specification
Every compiler is required to provide "C" linkage
A linkage specification shall occur only in namespace scope
All function types, function names and variable names have a language linkage See Richard's Comment: Only function names and variable names with external linkage have a language linkage
Two function types with distinct language linkages are distinct types even if otherwise identical
Linkage specs nest, inner one determines the final linkage
Extern "C" is ignored for class members
At most one function with a particle name can have "C" linkage (regardless of namespace)
Extern "C" forces a function to have external linkage (cannot make it static) See Richard's comment: 'static 'inside 'extern "C"' is valid; an entity so declared has internal linkage, and so does not have a language linkage
Linkage from C ++ to objects defined in other versions ages and to objects defined in C ++ from other versions ages is implementation-defined and language-dependent. only where the object layout strategies of two language implementations are similar enough can such linkage be achieved


Used 'extern "C" 'before for dll (dynamic link library) files to make etc. main () function "exportable" so it can be used later in another executable from dll. maybe an example of where I used to use it can be useful.

DLL

#include 
  
   #include 
   
    using namespace std;#define DLL extern "C" __declspec(dllexport)//I defined DLL for dllexport functionDLL main (){    MessageBox(NULL,"Hi from DLL","DLL",MB_OK);}
   
  

EXE

#include 
  
   #include 
   
    using namespace std;typedef LPVOID (WINAPI*Function)();//make a placeholder for function from dllFunction mainDLLFunc;//make a variable for function placeholderint main(){    char winDir[MAX_PATH];//will hold path of above dll    GetCurrentDirectory(sizeof(winDir),winDir);//dll is in same dir as exe    strcat(winDir,"\\exmple.dll");//concentrate dll name with path    HINSTANCE DLL = LoadLibrary(winDir);//load example dll    if(DLL==NULL)    {        FreeLibrary((HMODULE)DLL);//if load fails exit        return 0;    }    mainDLLFunc=(Function)GetProcAddress((HMODULE)DLL, "main");    //defined variable is used to assign a function from dll    //GetProcAddress is used to locate function with pre defined extern name "DLL"    //and matcing function name    if(mainDLLFunc==NULL)    {        FreeLibrary((HMODULE)DLL);//if it fails exit        return 0;    }    mainDLLFunc();//run exported function     FreeLibrary((HMODULE)DLL);}
   
  

% %
Extern "C" is a linkage specification which is used to call C functions in the Cpp source files. we can call C functions, write Variables, & include headers. function is declared in extern entity & it is defined outside. syntax is

Type 1:

extern "language" function-prototype

Type 2:

extern "language"{     function-prototype};

Eg:

#include
  
   using namespace std;extern "C"{     #include
   
        // Include C Header     int n;               // Declare a Variable     void func(int,int);  // Declare a function (function prototype)}int main(){    func(int a, int b);   // Calling function . . .    return 0;}// Function definition . . .void func(int m, int n){    //    //}
   
  

Related Article

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.