乐闻世界logo
搜索文章和话题

Call a C function from C++ code

1个答案

1

Calling C functions from C++ programs is a common requirement, especially when using existing C code libraries. To call C code from C++, it is crucial to ensure that the C++ compiler processes the C code in a C manner, which is typically achieved using the extern "C" declaration.

Step 1: Prepare the C Function

First, we need a C function. Suppose we have a simple C function for calculating the sum of two integers, with the code as follows (saved as math_functions.c):

c
// math_functions.c #include "math_functions.h" int add(int a, int b) { return a + b; }

Additionally, we need a header file (math_functions.h) so that both C and C++ code can reference this function:

c
// math_functions.h #ifndef MATH_FUNCTIONS_H #define MATH_FUNCTIONS_H #ifdef __cplusplus extern "C" { #endif int add(int a, int b); #ifdef __cplusplus } #endif #endif

Step 2: Calling C Functions from C++ Code

Now we create a C++ file (main.cpp) to call the aforementioned C function:

cpp
// main.cpp #include <iostream> #include "math_functions.h" int main() { int result = add(10, 20); std::cout << "The result of adding 10 and 20 is " << result << std::endl; return 0; }

In this example, extern "C" tells the C++ compiler that this code is written in C, so the compiler processes it according to C's compilation and linking rules. This is necessary because C++ performs name mangling, while C does not. Using this declaration directly avoids linker errors due to missing symbols.

Step 3: Compilation and Linking

You need to compile these codes separately using the C and C++ compilers, then link them together. Using GCC, you can do the following:

bash
gcc -c math_functions.c -o math_functions.o g++ -c main.cpp -o main.o g++ math_functions.o main.o -o main

Alternatively, if you use a single command:

bash
g++ main.cpp math_functions.c -o main

Here, .c files are automatically processed by the C compiler, while .cpp files are processed by the C++ compiler.

Summary

By using the above method, you can seamlessly call C functions within C++ programs. This technique is particularly useful for integrating existing C libraries into modern C++ projects. Simply ensure that the correct extern "C" declaration is used, and properly compile and link modules written in different languages.

2024年6月29日 12:07 回复

你的答案