How to call C function from C++ code?

Answer: Calling C function from C++ code is really simple. There may be a chance in software projects where mixing C and C++ code in the same program is required. One of the standard way, is to put C functions into a C header file, in extern “C” block. Notice how C++ macro has been used. For example

#ifdef __cplusplus
extern "C"
{
#endif
     //some functions here
     //functionOne();
    //functionsTwo();

#ifdef __cplusplus
}
#endif

This way, supports for both C and C++ compiler. It specifies the linkage specification that how C or C++ compiler has to link. Whenever C++ compiler, find this macro, it compiles the functions in C –style.

Here is C++ code example to call C function from C++ code :

//header file c-function-header.h

#ifndef __TEST_H__
#define __TEST_H__

#include 

#ifdef __cplusplus
extern "C" {
#endif

	void C_function();

#ifdef __cplusplus
}
#endif

#endif/*__TEST_H__*/
// c file
#include "c_func_header.h"

void C_function(){

	printf("This is C function...\n");
}
//main.cpp
/* This is the CPP sample to call C API */

#include "c_func_header.h"//include c header file here
#include
using namespace std;
  
int main(){

	cout<<"Calling C function from C++ \n";
	C_function();
	cout<<"Called C function successfuly \n";

	return 0;
}

Related Posts