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.

Hiring? Job Hunting? Post a JOB or your RESUME on our JOB BOARD >>

Subscribe to our newsletter for more free interview questions.