0

How do you call C functions from C++?

 2 years ago
source link: https://www.programmerinterview.com/c-cplusplus/how-do-you-call-c-functions-from-c/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

How do you call C functions from C++?

In order to call a C function from C++ code, you would use the “extern “C”” keyword when declaring the function in C. Then, you would call the function just like you would call any other function. An example will help clarify this:

/*this is what the C++ code would look like
   for the declaration of the foo function, which 
   is defined somewhere else in C code: */

extern "C" void foo( );	

And then to call the function in the C++ code, it would look like this:

//the declaration:
extern "C" void foo();

void main()
{
  // the function call:
  foo( );
}

What if we want to declare multiple C functions at once in our C++ code?

If you have more than one C functions that you would like to call from your C++ code, then it would be best to group them and declare them like this:

/* this is inside the C++ code,
     if we want to access multiple C functions
     from C++ then we can declare them like this:
*/
extern "C" {	
  
		int foo( );

		double foobar();
	};	

And then those functions could be called just like we showed above.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK