Friday, September 11, 2009

Inter-working with C/ C++ files

There are some times in the product development, especially in porting projects, and where we need to use the existing source codes, we may have to co-work with both C and C++ files, then we need to make them inter-work. Here I will show you how you can achieve that,

Accessing the C functions and data in C++ files.

supposed assume there is function func_c in a C file, my_file.c

void func_c(void)
{
    printf("I am a C function!");
}

to access this inside a C++ file, we need to declare it as shown below.

extern "C" void func_c(void);

The same methods can be followed for accessing all kind of data structures and variables.

Accessing C++ functions and Data Structures in C files.

Here things are other way round, just because C files does not take the key word extern "C", so all things need to be inside the C++ files, for C files its just another extern function or data.

So if I have a function func_cpp(void) as shown below, in my_file.cpp, it needs to be decalred as shown below

extern "C" void func_cpp(void)
{
    cout << "I am in C++ function";
}

To access this function inside the C file, just declare it as extern as you would normally do.

extern void func_cpp(void)

Hope it helps!

No comments:

Post a Comment