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:

functions.h

#ifndef MYAPP_FUNCTIONS_H
#define MYAPP_FUNCTIONS_H

int add(int x, int y);

#endif

functions.c

#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":

main.cpp

#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.