![]() |
VOOZH | about |
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.
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.
extern "C" {
Function_Name()
variable
}
where:
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:
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.o2. Compile main.cpp and link it with the object file
g++ main.cpp functions.o -o my_program3. Run the executable file to get the output using the below command
./my_programNote: Your C and C++ file must be present in the same environment.
Let us define the C file first from where we will export the variables and functionalities:
Now in the Cpp file we will use the functionalities defined in the C file:
Output
Hello GeeksTime Complexity: O(1)
Auxiliary Space: O(1)