only cpp compiler has defined cpluscplus.
#ifdef __cplusplus
extern "C" {
#endif
In cpp code if we want a function that will be callable from C program.We need declaration like this
cpp file.
#include
extern "C" void hello() {
std::cout << "hello" << '\n';
}
A function declared as extern "C" uses the function name as symbol name, just as a C function. For that reason, only non-member functions can be declared as extern "C", and they cannot be overloaded.
C++ compiler uses a technique termed name mangling which incorporates the function name with its signature (list of arguments) in order to create a unique name for it, even in case of overloading (this technique is used both for external function and class member functions).
In order to enforce the compiler to avoid name mangling, a global function has to be declared as extern "C":
extern "C" void f(int); //now the generated name is identical to the one given by the programmer.
How to include non standard C header file in C++ code?
//C++ code
extern "C" {
// Get declaration for
#include "my-C-code.h"
}
int main()
{
f(7, 'a');
...
}
To make it easier its better to change header file itself .
at top putting
#ifdef __cplusplus
extern "C" {
#endif
At end put
#ifdef __cplusplus
}
#endif
Now it .h can be included in cPP simply
// Get declaration for
#include "my-C-code.h"
int main()
{
f(7, 'x');
...
}
--------------
if we dont want to include whole file individual function can be declared
extern "C" void f(int i, char c);
Or a group can be :
extern "C" {
void f(int i, char c);
int f2(char* s, char const* s2);
double f3(double a, double b);
}
All blogs are Nice. Great hard work, thanks for sharing your hard work
ReplyDeletec++ interview questions
salesforce interview questions
bootstrap interview questions
spring interview questions and answers for experienced
Very nice blog, Thank you for providing good information.
ReplyDeletepython training in bangalore | python online Training
artificial intelligence training in bangalore | artificial intelligence online training
machine learning training in bangalore | machine learning online training
uipath-training-in-bangalore | uipath online training
blockchain training in bangalore | blockchain online training
aws training in Bangalore | aws online training
data science training in bangalore | data science online training
hadoop training in bangalore | hadoop online training
iot training in bangalore | iot online training