Running C++ code from a C program

Posted: 11th April 2013 by Tim in C, C++
Tags: , , , , , , , ,

There are times where you have a C program but would like to call code written in C++. This is quite easy to do, and if done right will work on all (compliant) compilers on multiple platforms.

To achieve this, you need to declare your function(s) to look like C functions in a header file. By that I mean that they can only use types recognised by C (int, double, etc). The function definition can use C++ to it’s heart’s content, but from the outside it needs to look like C. The functions need to be declared as extern "C" when compiled under C++, as shown in the example below.

Next, you need to define your function(s) in a separate .cc or .cpp file. This file is pure C++ and can contain any C++ syntax you like.

Finally, the calling code simply needs to include the header file and call the routine.

To build your program, first compile the C++ code into an object (.o) file using a C++ compiler, then build your main program with the .o file included like you would with any other .o file.

Let’s look at small example. In this example I perform factorial calculations on integers and floats. I didn’t want to duplicate the code for this work, so I wrote a templated function in C++ and provided C-style wrappers to allow this to be called from C.


// the two #ifdef blocks allow extern "C" to be used when
// compiling as C++ but not when compiling as C
#ifdef __cplusplus
extern "C" {

int factorial_int(int x);
float factorial_float(float f);

#ifdef __cplusplus
} // extern "C"

#include "cplusplus.h"

template <typename T>
int calcFactorial(T number)
    if (number <= 1)
        return 1;
    return number * calcFactorial(number - 1);

// wrapper function for int calculations
int factorial_int(int x)
    return calcFactorial(x);

// wrapper function for float calculations
float factorial_float(float f)
    return calcFactorial(f);


#include "cplusplus.h"
#include <stdio.h>

int main()
    int n = 10;
    printf("%d! = %d\n", n, factorial_int(n));

    float f = 10;
    printf("%f! = %f\n", f, factorial_float(f));

    return 0;

You can then build this in gcc:
g++ -c -o cc.o
gcc -o prog_name main.c cc.o

And you’re done! Running the program will result in this output:
10! = 3628800
10.000000! = 3628800.000000

  1. Robert says:

    Very useful. Great site.