This post has already been read 2099 times!

There are times when it is required to mix the C and C++ code together. For example, while using a legacy C code or while using a specific C library the provides your C++ code with some specific functionality. So, some special steps are to be taken care of when using C code in C++ file or vice versa.

This article, through some examples discusses the steps required to mix C/C++ code.

1. Call C functions from C++

In this section we will discuss on how to call C functions from C++ code.

Here is the C code (Cfile.c):

#include 

void f(void)
{
    printf("\n This is a C code\n");
}

The first step is to create a library of this C code. The following steps create a shared library :

$ gcc -c -Wall -Werror -fPIC Cfile.c
$ gcc -shared -o libCfile.so Cfile.o

The shared library libCfile.so is produced as a result of above two commands.

Here is the main C++ code (main.cpp) :

#include 

extern "C" {
void f();
}

void func(void)
{
    std::cout<<"\n being used within C++ code\n";
}

int main(void)
{
    f();
    func();
    return 0;
}

The C function f() is declared within the notation extern “C” to tell the cpp compiler that it has C type linkage.

Now, compile the code (make sure that the shared library libCfile.so is linked to the code):

$ g++ -L/home/himanshu/practice/ -Wall main.cpp -o main -lCfile

Before running the executable make sure that the path of shared library is contain in the environment variable LD_LIBRARY_PATH.

$ export LD_LIBRARY_PATH=/home/himanshu/practice:$LD_LIBRARY_PATH

Now run the executable ‘main’ :

$ ./main

2. Call C++ functions from C

In this section we will discuss on how to call C++ functions from C code.
Here is a C++ code (CPPfile.cpp) :

#include 

void func(void)
{
    std::cout<<"\n This is a C++ code\n";
}

We will see how the function func() can be called from a C code.

The first step for this is to change the declaration/definition of this function by introducing the notation extern “C”.

#include 

extern "C" void func(void)
{
    std::cout<<"\n This is a C++ code\n";
}

The next step is to create a library out of the code above. The following steps create a shared library:

 g++ -c -Wall -Werror -fPIC CPPfile.cpp
$ g++ -shared -o libCPPfile.so CPPfile.o

The above commands should result in libCPPfile.so shared library.

Here is main code in C language (main.c) :

#include 

extern void func(void);

void f(void)
{
    printf("\n being used within C code\n");
}

int main(void)
{
    func();
    f();
    return 0;
}

Please note that the C++ function is declared as extern here.

Compile the C code (main.c) like this:

gcc -L/home/himanshu/practice/ -Wall main.c -o main -lCPPfile

and add the current directory path to the environment variable LD_LIBRARY _PATH

export LD_LIBRARY_PATH=/home/himanshu/practice:$LD_LIBRARY_PATH

Now run the executable ‘main’ :

$ ./main

Comments are closed.

Post Navigation