Call C Function From C++

Call C Function From C++

Integrating C code into a C++ project is a common scenario, especially when you're dealing with legacy codebases or need to leverage existing libraries written in C. While C and C++ are closely related, there are some differences that can complicate the process. This tutorial explains how to call C function from C++.

Let's say we have a simple C function which calculates the sum of two integers:



int add(int x, int y);



#include "functions.h"

int add(int x, int y) {
    return x + y;

In the C++ code, include the C header file and wrap it with extern "C":


#include <iostream>

extern "C" {
#include "functions.h"

int main()
    std::cout << add(1, 2) << std::endl;

    return 0;

C functions integration into C++ codebase is pretty straightforward. This approach allows you to benefit from existing C code while taking advantage of the object-oriented features and type safety provided by C++.

Leave a Comment

Cancel reply

Your email address will not be published.