C++ call C function example details

  • 2020-05-26 09:47:38
  • OfStack

C++ call C function example details

Preface: when I saw extern "C" before, I simply knew it was related to external links, but I didn't fully understand its meaning.

First, why use the extern "C" modifier?

C++ calls functions in other languages. Since the compiler does not have the same mechanism for generating functions, it needs special handling before it can be called. To call a function in the C language, you need to say extern "C" where the function is declared. If you do not use this statement, the compiler will report the following error when linking.

Test. obj: error LNK2019: non-resolvable external symbol "void s 25en DeleteStack(struct _Node *)" (? DeleteStack @YAXPAU_Node @@Z), which is referenced in the function _main.

And then how do you use it?

How should you use this statement?

Initially, I simply used this statement in front of the C++ source file, but there was still an error, and it was reported at compile time.


error C2732:  Link specification and" DeleteStack Early normative conflicts.  

Why did this error occur? Since the C++ source file has already introduced the C header file, in the header file, there is no extern modifier when the function is declared, but here there is an extern modifier, so there is a conflict. There are two solutions.

1. Add the extern modifier to the C header file.

You can't just add. Because the C source also contains this header file, an error occurs when compiling the C source file. Therefore, you need a mechanism to distinguish between compiling C and C++ files. The method is as follows:


#ifdef __cplusplus 
extern "C" 
#endif 
 void DeleteStack(Stack stack); 


This is because the preprocessor name is automatically defined while building C++ file, while building C is not. So the symbol extern "C" is only used when C++ is compiled.

In addition, the link indicates that extern "C" has both single and compound forms. The above is a single form. The composite form can declare several functions as extern "C" at the same time.


extern "C" { 
void DeleteStack(Stack stack); 
void PrintStack(Stack stack); 
void Pop(Stack stack); 
} 

Add the preprocessor name as follows:


#ifdef __cplusplus 
extern "C" { 
#endif 
 
void DeleteStack(Stack stack); 
void PrintStack(Stack stack); 
void Pop(Stack stack); 
 
#ifdef __cplusplus 
} 
#endif 

2. Write an C++ style header file and add the extern modifier here.

Use method 1. Easy. But if the header file is written by someone else, you can't change it. That's where the other method comes in. You can do this by defining C++ your own header file called "CStack.h"


// CStack.h 
extern "C" { 
#include "Stack.h"; 
} 

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: