library

Using attribute((weak)) weak symbols in gcc compilation of dynamic library so on Linux system

First explain the code structure: there are three source files, two dynamic library so sources: lib1.c and lib2.c, each exporting one library function (gcc exports by default, unlike Windows msvc which requires explicit dllexport), and one main program source: main.c, which calls the exported functions of the two dynamic libraries, as follows:

lib1.c

#include <stdio.h>

void lib1_func(const char* from)
{
        printf("lib1 func from %s\n", from);
}

lib2.c

#include <stdio.h>

void lib2_func(const char* from)
{
        printf("lib2 func from %s\n", from);
}

main.c

#include <stdio.h>

void lib1_func(const char* from);
void lib2_func(const char* from);

int main()
{
        printf("hello from main\n");
        lib1_func("main");
        lib2_func("main");
        return 0;
}
Continue reading…

Record of a Linux system C++ dynamic library global symbol name conflict

First, a simple description of the situation: there are three code files, one main executable and two dynamic libraries. The structure is similar to the weak symbol example:

#include <string>

std::string g_name;

void init_name_lib1()
{
    g_name = "lib1";
}

const char* get_name_lib1()
{
    return g_name.c_str();
}
#include <string>

std::string g_name;

void init_name_lib2()
{
    g_name = "lib2";
}

const char* get_name_lib2()
{
    return g_name.c_str();
}
#include <iostream>

void init_name_lib1();
void init_name_lib2();
const char* get_name_lib1();
const char* get_name_lib2();

int main()
{
    init_name_lib1();
    init_name_lib2();

    std::cout << "name from lib1: " << get_name_lib1() << std::endl;
    std::cout << "name from lib2: " << get_name_lib2() << std::endl;

    return EXIT_SUCCESS;
}
Continue reading…