Lesson 26-C++ Linking and Loading Libraries

Creating a Shared Library

C++ code writing
First, we need to write a simple C++ function and then compile it into a shared library.

File: libexample.h

#ifndef LIBEXAMPLE_H
#define LIBEXAMPLE_H

class Example {
public:
    void sayHello();
};

#endif // LIBEXAMPLE_H

File: libexample.cpp

#include "libexample.h"
#include <iostream>

void Example::sayHello() {
    std::cout << "Hello from shared library!" << std::endl;
}

Compile into a shared library
Use the g++ compiler to compile the above code into a shared library.

g++ -shared -o libexample.so libexample.cpp -fPIC

The -shared flag tells the compiler to generate a shared library, and -fPIC ensures the code is position-independent, which is important for shared libraries.

Using the Shared Library

Using it in a program
Next, we create a main program to use this shared library.

File: main.cpp

#include "libexample.h"

int main() {
    Example example;
    example.sayHello();
    return 0;
}

Link and run
When compiling and linking the main program, you need to specify the location of the shared library.

g++ main.cpp -L. -lexample

Here, -L. specifies the library search path as the current directory, and -lexample tells the linker to link the library named example.

Dynamic Loading and Usage

In some cases, you may need to dynamically load and use a library at runtime. This is typically done using functions like dlopen, dlsym, dlclose, etc.

File: dynamic_load_example.cpp

#include <dlfcn.h>
#include <iostream>

int main() {
    void* handle = dlopen("./libexample.so", RTLD_LAZY);
    if (!handle) {
        std::cerr << "Cannot open library: " << dlerror() << std::endl;
        return 1;
    }

    typedef void (*SayHello)();
    SayHello sayHello = (SayHello)dlsym(handle, "sayHello");
    const char* dlsym_error = dlerror();
    if (dlsym_error) {
        std::cerr << "Cannot load symbol 'sayHello': " << dlsym_error << std::endl;
        dlclose(handle);
        return 1;
    }

    sayHello();

    dlclose(handle);
    return 0;
}

This program demonstrates how to open a shared library, obtain a function pointer from the library, and call that function.

Handling More Complex Dynamic Library Operations

Multiple Classes and Functions

In real-world applications, a shared library may contain multiple classes and functions. We can extend the previous example to demonstrate this.

File: libexample.h

#ifndef LIBEXAMPLE_H
#define LIBEXAMPLE_H

class Example {
public:
    void sayHello();
    void sayGoodbye();
};

#endif // LIBEXAMPLE_H

File: libexample.cpp

#include "libexample.h"
#include <iostream>

void Example::sayHello() {
    std::cout << "Hello from shared library!" << std::endl;
}

void Example::sayGoodbye() {
    std::cout << "Goodbye from shared library!" << std::endl;
}

Dynamically Loading Multiple Functions

Modify dynamic_load_example.cpp to dynamically load multiple functions.

File: dynamic_load_example.cpp

#include <dlfcn.h>
#include <iostream>

int main() {
    void* handle = dlopen("./libexample.so", RTLD_LAZY);
    if (!handle) {
        std::cerr << "Cannot open library: " << dlerror() << std::endl;
        return 1;
    }

    typedef void (*SayHello)();
    typedef void (*SayGoodbye)();

    SayHello sayHello = (SayHello)dlsym(handle, "sayHello");
    const char* dlsym_error = dlerror();
    if (dlsym_error) {
        std::cerr << "Cannot load symbol 'sayHello': " << dlsym_error << std::endl;
        dlclose(handle);
        return 1;
    }

    SayGoodbye sayGoodbye = (SayGoodbye)dlsym(handle, "sayGoodbye");
    dlsym_error = dlerror();
    if (dlsym_error) {
        std::cerr << "Cannot load symbol 'sayGoodbye': " << dlsym_error << std::endl;
        dlclose(handle);
        return 1;
    }

    sayHello();
    sayGoodbye();

    dlclose(handle);
    return 0;
}

Cross-Platform Support

Windows Platform

On the Windows platform, dynamic libraries are called DLLs (Dynamic Link Libraries). The method of loading and using DLLs is slightly different.

File: libexample.h

#ifndef LIBEXAMPLE_H
#define LIBEXAMPLE_H

#ifdef _WIN32
#define DLL_EXPORT __declspec(dllexport)
#else
#define DLL_EXPORT
#endif

class DLL_EXPORT Example {
public:
    void sayHello();
    void sayGoodbye();
};

#endif // LIBEXAMPLE_H

File: libexample.cpp

#include "libexample.h"
#include <iostream>

void Example::sayHello() {
    std::cout << "Hello from shared library!" << std::endl;
}

void Example::sayGoodbye() {
    std::cout << "Goodbye from shared library!" << std::endl;
}

Compile into DLL

Compile into a DLL on Windows:

cl /LD /Fe:libexample.dll libexample.cpp

Using the DLL

Using the DLL on Windows:

File: main.cpp

#include "libexample.h"

int main() {
    Example example;
    example.sayHello();
    example.sayGoodbye();
    return 0;
}

Compile and link:

cl main.cpp libexample.lib

Exception Handling

When dynamically loading libraries, it is recommended to add an exception handling mechanism.

File: dynamic_load_example.cpp

#include <dlfcn.h>
#include <iostream>
#include <stdexcept>

int main() {
    try {
        void* handle = dlopen("./libexample.so", RTLD_LAZY);
        if (!handle) {
            throw std::runtime_error("Cannot open library: " + std::string(dlerror()));
        }

        typedef void (*SayHello)();
        typedef void (*SayGoodbye)();

        SayHello sayHello = (SayHello)dlsym(handle, "sayHello");
        const char* dlsym_error = dlerror();
        if (dlsym_error) {
            throw std::runtime_error("Cannot load symbol 'sayHello': " + std::string(dlsym_error));
        }

        SayGoodbye sayGoodbye = (SayGoodbye)dlsym(handle, "sayGoodbye");
        dlsym_error = dlerror();
        if (dlsym_error) {
            throw std::runtime_error("Cannot load symbol 'sayGoodbye': " + std::string(dlsym_error));
        }

        sayHello();
        sayGoodbye();

        dlclose(handle);
    } catch (const std::exception& e) {
        std::cerr << "Error: " << e.what() << std::endl;
        return 1;
    }

    return 0;
}

Version Control

For large projects, it is recommended to use version control to manage the compatibility and stability of the library.

File: libexample.h

#ifndef LIBEXAMPLE_H
#define LIBEXAMPLE_H

#define LIBEXAMPLE_MAJOR_VERSION 1
#define LIBEXAMPLE_MINOR_VERSION 0
#define LIBEXAMPLE_PATCH_VERSION 0

#ifdef _WIN32
#define DLL_EXPORT __declspec(dllexport)
#else
#define DLL_EXPORT
#endif

class DLL_EXPORT Example {
public:
    void sayHello();
    void sayGoodbye();
};

#endif // LIBEXAMPLE_H

In this way, compatibility checks can be performed between different versions.

Share your love