For users and scholars who first came into contact with the C ++ language, it is very important to understand the concept of the C ++ language. let's first talk about what the C ++ language is, C ++ is a widely used computer programming language.
As a language to be compatible with C, C ++ retains the features of some procedural languages, which are known as "incomplete Ground Objects "), therefore, 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.
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 */
So:
- #ifdef __cplusplus
- extern "C" {
- #endif
- #ifdef __cplusplus
- }
- #endif
In the header file of the C language, the external function can only be specified as the extern type. The C language does not support the extern "C" declaration. when the c file contains extern "C", a compilation syntax error occurs.
- /* C 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;
- }
When C references functions and variables in C ++, the header file of C ++ needs to add extern "C ", however, you cannot directly reference this header file that declares extern "C" in C. You should only declare the extern "C" function defined in C ++ as the extern type.
- // 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
- /* Compilation errors: # include "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 really understand the usage of referencing C Functions and C ++ functions from C ++ described in this section. Pay special attention to the sample code given in section 4th.
- Introduction to C ++
- Summary Notes on learning and exploring C ++ library functions
- Basic Conception and method of C ++ Class Library Design
- Does C ++ really have market value?
- Basic Conception and method of C ++ Class Library Design