Can I Mix C and C++ Code in the Same Project?

C and C++ both are very popular programming languages. There can be many situations when you might have to export some functionalities that are written in C programming language into your C++ code. Now the biggest question arises while making any project in C and C++ is that- “Can we Mix C and C++ Code in the Same Project? The answer is Yes, and in this article, we will learn how we can mix C and C++ code in the same project.

Mixing C and C++ Code in the Same Project

To mix C and C++ code in the same project we can use the extern keyword. The extern keyword is a special keyword in C and C++ that extends the visibility of the variables and the function declared in a source file to another source file. We can use this extern keyword to export the variables and functions from our C file and then we can use them in the cpp file. Following is the syntax to use the extern keyword for importing function in C++ source file from a C source file.

Syntax for extern

extern "C" {
Function_Name()
variable
}

where:

  • Function_Name(): is the name of the function you want to import from the C file.
  • variable: is the name of the variable you want to import from the C file.

To mix C and C++ together we can’t simply compiler the C++ code. We must follow the below steps to mix the c and C++ code:

Steps to Compile C and C++ code in the same project

Let us consider the name of the c file is functions.c and the name of the cpp files is main.cpp:

1. Compile functions.c into an object file using the below command:

gcc -c functions.c -o functions.o

2. Compile main.cpp and link it with the object file

g++ main.cpp functions.o -o my_program

3. Run the executable file to get the output using the below command

./my_program

Note: Your C and C++ file must be present in the same environment.

C++ Program to Mix C and C++ Code in the Same Project

Let us define the C file first from where we will export the variables and functionalities:

C
#include <stdio.h>

void myFunction() {
    printf("Hello Beginner");
}

Now in the Cpp file we will use the functionalities defined in the C file:

C++
#include <iostream>
using namespace std;
// Declaration of the C function
extern "C" {
    void myFunction(); 
}

int main() {
    // Calling the C function from C++
    myFunction(); 
    return 0;
}

Output

Hello Beginner

Time Complexity: O(1)
Auxiliary Space: O(1)