The answer is to compile C shared libraries using the -fPIC and -shared flags. First write header files and source files, such as example.h and example.cpp; then use g -fPIC -c example.cpp to generate position-independent target files; then create a shared library through g -shared -o libexample.so example.o; finally include the header file in the main program and link the library, add -L. -lexample when compiling, and ensure that the library file can be found at runtime, such as setting LD_LIBRARY_PATH or using the -Wl, -rpath option.
To create a shared library in C, you need to compile your code into a shared object file (on Linux/Unix) or a dynamic-link library (on Windows). The process involves writing your library code, compiling it with position-independent code (PIC), and linking it properly so it can be used by other programs at runtime.
Write Your Library Code
Start by defining the functionality you want in your shared library. Create header and source files as usual.
example.h#ifndef EXAMPLE_H #define EXAMPLE_H void greet(); int add(int a, int b); #endifexample.cpp
#include "example.h" #include <iostream> void greet() { std::cout << "Hello from shared library!\n"; } int add(int a, int b) { return ab; }
Compile to Position-Independent Code
Shared libraries must be compiled with position-independent code (PIC) so they can be loaded at any memory address. Use the -fPIC flag when compiling.
g -fPIC -c example.cpp
This generates example.o , an object file suitable for a shared library.
Create the Shared Library
Link the object file into a shared library using the -shared flag.
g -shared -o libexample.so example.o
This creates libexample.so on Linux (or libexample.dylib on macOS with different flags, or example.dll on Windows using MinGW or MSVC).
You can combine both steps:
g -fPIC -shared -o libexample.so example.cpp
Use the Shared Library in a Program
Create a main program that uses your library.
main.cpp#include "example.h" int main() { greet(); std::cout << "5 3 = " << add(5, 3) << "\n"; return 0; }
Compile and link against the shared library:
g -I. main.cpp -L. -lexample -o main
- -I. tells the compiler to look for headers in the current directory
- -L. tells the linker to look for libraries here
- -lexample links against libexample.so
Run the Program
Before running, make sure the system can find the shared library. You may need to set the library path:
export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH
(Linux)
./main
On some systems, you can also use rpath to embed the library path:
g -I. main.cpp -L. -lexample -Wl,-rpath=. -o main
Basically, just compile with -fPIC and -shared, then link and ensure the runtime loader can locate the .so file. That's how you make a usable C shared library.
The above is the detailed content of How to create a shared library in C. 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)

InstallaC compilerlikeg usingpackagemanagersordevelopmenttoolsdependingontheOS.2.WriteaC programandsaveitwitha.cppextension.3.Compiletheprogramusingg hello.cpp-ohellotogenerateanexecutable.4.Runtheexecutablewith./helloonLinux/macOSorhello.exeonWi

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.

An abstract class is a class containing at least one pure virtual function. It cannot be instantiated and must be inherited as a base class. The derived class needs to implement all its pure virtual functions, otherwise it will still be an abstract class. 1. Pure virtual functions are declared by virtual return type function name()=0; to define interface specifications; 2. Abstract classes are often used for unified interface design, such as area(), draw(), etc., to implement polymorphic calls; 3. Virtual destructors must be provided for abstract classes (such as virtual~Shape()=default;) to ensure that derived class objects are correctly released through base class pointers; 4. After the derived class inherits, pure virtual functions must be rewrite, such as Rectangle and Circle to implement area() to calculate their respective areas; 5.

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

Real-time systems require deterministic responses, because correctness depends on the result delivery time; hard real-time systems require strict deadlines, missed will lead to disasters, while soft real-time allows occasional delays; non-deterministic factors such as scheduling, interrupts, caches, memory management, etc. affect timing; the construction plan includes the selection of RTOS, WCET analysis, resource management, hardware optimization and rigorous testing.

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.
