hyunsik-yoon / study

Personal repository for self-study
Apache License 2.0
0 stars 0 forks source link

Compilation & Linking procedure #151

Open hyunsik-yoon opened 1 year ago

hyunsik-yoon commented 1 year ago

참조: https://www.youtube.com/watch?v=N2y6csonII4 https://www.youtube.com/watch?v=UdMRcJwvWIY https://www.youtube.com/watch?v=8pwbFFBmM-k https://stackoverflow.com/questions/2937273/questions-about-name-mangling-in-c

hyunsik-yoon commented 1 year ago

compilation

hyunsik-yoon commented 1 year ago

link

image

static linking

dynamic linking

symbol binding

shared library naming convertion

static lib 로 컴파일한 사례

image image

dynamic link 를 하는 사례

image image image image image
hyunsik-yoon commented 1 year ago

loader

image
hyunsik-yoon commented 1 year ago

ABI (Application Binary Interface)

hyunsik-yoon commented 1 year ago

When OS fails to link dynamic lib

1. Use LD_LIBRARY_PATH:

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/path/to/your/library/

2. Use rpath or runpath:

gcc -o myprog myprog.c -Wl,-rpath,/path/to/your/library/

3 Use LD_PRELOAD:

export LD_PRELOAD=/path/to/your/library/libYourLib.so
hyunsik-yoon commented 1 year ago

dynamic loading inside code

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

// Assume libfoo.so defines a function with the following prototype:
// void foo();

int main() {
    // Load the shared library.
    void* handle = dlopen("libfoo.so", RTLD_LAZY);
    if (!handle) {
        std::cerr << "Cannot open library: " << dlerror() << '\n';
        return 1;
    }

    // Clear any existing error
    dlerror();

    // Load the symbol (function).
    typedef void (*foo_t)();

    // cast to correct type (takes a guess and double-checks with a run-time dynamic cast)
    foo_t foo = (foo_t) dlsym(handle, "foo");
    const char *dlsym_error = dlerror();
    if (dlsym_error) {
        std::cerr << "Cannot load symbol 'foo': " << dlsym_error << '\n';
        dlclose(handle);
        return 1;
    }

    // Now we can call the function using the function pointer
    (*foo)();

    // Unload the library.
    if (dlclose(handle) != 0) {
        std::cerr << "Cannot close library: " << dlerror() << '\n';
        return 1;
    }

    return 0;
}
$ g++ main.cpp -ldl -o main