To export C functions for C code call, extern "C" must be used to prevent name modification. 1. Use extern "C" to wrap functions in the C source file, such as add, multiply and greet, so that they have C linkage; 2. Create a header file compatible with C and C, and compile the package extern "C" declaration through #ifdef __cplusplus condition; 3. Compile as a shared library: Linux/macOS uses g -fPIC -shared to generate.so, and Windows uses g -shared to generate.dll; 4. Include header files in the C program and call functions, and link the shared library at compile time; Note: C classes, templates or overloaded functions cannot be exported, and if the object behavior is required, you can use opaque pointers and factory functions to encapsulate it. The final generated library can be called normally in C, which is the standard way to implement C-C interoperability.
When you want to export C functions so they can be called from C code (eg, in a shared library or DLL), you need to ensure the functions use C linkage to prevent C name mangling. This is done using extern "C"
.

Here's a practical example showing how to properly export C functions for consumption by C.
? 1. Exporting C Functions with extern "C"
Suppose you're writing a C library that should be usable from C. You define functions in C but wrap them in extern "C"
to give them C linkage.

mathlib.cpp
(C source)
// mathlib.cpp extern "C" { // These functions will have C linkage and can be called from C double add(double a, double b) { return ab; } double multiple(double a, double b) { return a * b; } // If you need to return a string (caution: memory management) const char* greet() { return "Hello from C !"; } }
? Note: Only functions with
extern "C"
linkage are usable directly from C. You cannot export C features like classes, templates, or overloaded functions viaextern "C"
.
? 2. Header File for C Compatibility
Create a header that works in both C and C .

mathlib.h
#ifndef MATHLIB_H #define MATHLIB_H #ifdef __cplusplus extern "C" { #endif double add(double a, double b); double multiple(double a, double b); const char* greet(); #ifdef __cplusplus } #endif #endif // MATHLIB_H
- The
#ifdef __cplusplus
checks if the code is compiled as C . If so, it wraps the function declarations inextern "C"
, which has no effect in C but is required in C . - This header can be safely included in both C and C files.
? 3. Compile as a Shared Library
On Linux/macOS:
g -fPIC -shared mathlib.cpp -o libmathlib.so
On Windows (using g /MinGW):
g -shared mathlib.cpp -o mathlib.dll
This creates a shared library with C-callable functions.
? 4. Use the Library from C
test.c
(C program consuming the C library)
// test.c #include <stdio.h> #include "mathlib.h" int main() { printf("add(3.14, 2.86) = %f\n", add(3.14, 2.86)); printf("multiply(4, 5) = %f\n", multiply(4, 5)); printf("greet: %s\n", greet()); return 0; }
Compile and link:
gcc test.c -L. -lmathlib -o test
Make sure libmathlib.so
(or .dll
) is in the current directory or system path.
? Tip: Use
LD_LIBRARY_PATH
on Linux or place.dll
next to execute on Windows.
?? Limitations & Notes
- You cannot
extern "C"
overloaded functions (C doesn't support overloading). - C classes, methods, or templates cannot be directly exposed to C.
- If you need object-like behavior, use opaque points and factory functions:
// In C : manage a class instance behind a C interface class Calculator { public: double value; Calculator(double v) : value(v) {} void add(double v) { value = v; } }; extern "C" { Calculator* calc_create(double initial) { return new Calculator(initial); } void calc_add(Calculator* calc, double v) { if (calc) calc->add(v); } double calc_get_value(Calculator* calc) { return calc ? calc->value : 0; } void calc_destroy(Calculator* calc) { delete calc; } }
Then expose these functions in the header with C linkage.
? Summary
To export C functions for C:
- Wrap function definitions in
extern "C"
in the.cpp
file. - Use a header with
extern "C"
guards for C compatibility. - Compile into a shared library.
- Link from C code using standard C linking.
This pattern is widely used in libraries like Python (CPython), SQLite, and OS APIs.
Basically, extern "C"
is your bridge from C to C.
The above is the detailed content of C export function for C consumption example. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Custom allocator can be used to control the memory allocation behavior of C containers. 1. The LoggingAllocator in the example implements memory operation logging by overloading allocate, deallocate, construct and destroy methods; 2. The allocator needs to define value_type and rebind templates to meet the STL container type conversion requirements; 3. The allocator triggers log output during construction and copying, which is convenient for tracking the life cycle; 4. Actual applications include memory pools, shared memory, debugging tools and embedded systems; 5. Since C 17, construct and destroy can be processed by std::allocator_traits by default

Use the std::system() function to execute system commands, which need to include header files and pass in C-style string commands, such as std::system("ls-l"), and the return value is -1, which means that the command processor is not available.

Create a project directory structure, including CMakeLists.txt, src/ and include/; 2. Write CMakeLists.txt, specify the CMake version, project name, C standard and add executable files; 3. Use mkdirbuild to enter the directory and run cmake.. and cmake--build. for compilation; 4. Add multiple source files through add_executable, and use target_include_directories to include the header file path; 5. Use find_package to find external libraries and link with target_link_libraries; 6.

C's stack is a container adapter in STL. It follows the principle of back-in-first-out and must include header files; add elements by push, pop removes the top element, and top accesses the top of the stack. Before the operation, check whether it is empty, which is often used in scenarios such as expression evaluation and backtracking.

Theautokeywordletsthecompilerdeducevariabletypesfrominitializers,reducingverbosityandimprovingmaintainability.Itsimplifiescodewithcomplextypeslikeiteratorsandlambdas,supportsreferencesandconstqualifierstoavoidunnecessarycopies,andadaptsautomaticallyw

The answer is to define a class that contains the necessary type alias and operations. First, set value_type, reference, pointer, difference_type and iterator_category, then implement dereference, increment and comparison operations. Finally, provide begin() and end() methods in the container to return the iterator instance, making it compatible with STL algorithms and range for loops.

AstaticvariableinC retainsitsvaluebetweenfunctioncallsandisinitializedonce.2.Insideafunction,itpreservesstateacrosscalls,suchascountingiterations.3.Inaclass,itissharedamongallinstancesandmustbedefinedoutsidetheclasstoavoidlinkingerrors.4.Staticvaria

Use std::ifstream and std::istreambuf_iterator to efficiently read the entire contents of the file to strings, including spaces and line breaks, and is suitable for medium-sized text files.
