Get the App
SLTechnology News&Howtos  ›  Development  › 

How does C++ handle global functions?

Shulou Source: shulou.com Published: 2022-06-02 09:42:29 09月15日 Update

This article mainly introduces "how C++ handles global functions". In daily operation, I believe many people have doubts about how C++ handles global functions. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "what is C++ 's way to handle global functions?" Next, please follow the editor to study!

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 C language, the external function can only be specified as extern type. The declaration of extern "C" is not supported in C language. When the extern "C" is included in the .c file, there will be a compilation syntax error.

/ * c language header file: cExample.h * / # ifndef C_EXAMPLE_H # define C_EXAMPLE_H extern int add (int XMagol int y); # endif / * c language implementation file: cExample.c * / # include "cExample.h" int add (int x Magi int y) {return x + y } / / C++ implementation file, call add:cppFile.cpp extern "C" {# include "cExample.h"} int main (int argc, char* argv []) {add (2jue 3); return 0;}

When referencing functions and variables in the C++ language in C, extern "C" should be added to the C++ header file, but the header file that declares extern "C" cannot be directly referenced in C language. Only the extern "C" function defined in C++ in the C file should be declared 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 / * this will cause compilation errors: # include "cExample.h" * / extern int add (int x, int y) Int main (int argc, char* argv []) {add (2,3); return 0; at this point, the study of "how C++ handles global functions" is over. I hope I can solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Tags: Files functions caching languages globals methods processing learning more types help compilation utility next lieutenant general variables articles methods are in the standard Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Shulou Tech Info Xiaomi Apple Shulou Technology