Quantcast
Viewing all articles
Browse latest Browse all 22113

g++ user-defined global new and delete operators on dynamically linked libraries

On g++, code from dynamically linked libraries uses operator delete from the main program. With the -Wl,-Bsymbolic option, the dynamically linked library used its own operator new but uses the main program's operator delete. Compiling using clang++ with the -Wl,-Bsymbolic option has the dynamically linked library using its own operator new and delete. On linux (ubuntu)

// base_program.cpp
#include <dlfcn.h>
#include <stdio.h>
#include <cstdlib>
typedef void dllFunc();

void *operator new(std::size_t count) {
    printf("base_program new\n");
    void *result = malloc(count);
    return result;
}
void *operator new[](std::size_t count) {
    printf("base_program new[]\n");
    void *result = malloc(count);
    return result;
}
void operator delete(void *ptr) noexcept {
    printf("base_program delete\n");
    free(ptr);
}
void operator delete[](void *ptr) noexcept {
    printf("base_program delete[]\n");
    free(ptr);
}

int main(int nArgs, char **args) {
    void *handle = dlopen(DLLFILE, RTLD_LAZY);
    dllFunc *func = (dllFunc*) dlsym(handle, "testFunc");
    printf("Linking with %s\n", DLLFILE);
    int *a = new int;
    delete a;
    func();
    printf("\n");
    return 0;
}
// linking.cpp
#include <stdio.h>
#include <cstdlib>
void *operator new(std::size_t count) {
    printf("linking new\n");
    void *result = malloc(count);
    return result;
}
void *operator new[](std::size_t count) {
    printf("linking new[]\n");
    void *result = malloc(count);
    return result;
}
void operator delete(void *ptr) noexcept {
    printf("linking delete\n");
    free(ptr);
}
void operator delete[](void *ptr) noexcept {
    printf("linking delete[]\n");
    free(ptr);
}

extern "C" void testFunc() {
    int *a = new int;
    delete a;
}
// build.sh
g++ -g -fPIC -DDLLFILE="\"linking_g.so\"" base_program.cpp -o base_program_g -ldl
g++ -g -fPIC -shared linking.cpp -o linking_g.so -Wl,-Bsymbolic

clang++ -g -fPIC -DDLLFILE="\"linking_clang.so\"" base_program.cpp -o base_program_clang -ldl
clang++ -g -fPIC -shared linking.cpp -o linking_clang.so -Wl,-Bsymbolic

Running ./build.sh; ./base_program_g; ./base_program_clang results in the following

Linking with linking_g.so
base_program new
base_program delete
linking new
base_program delete

Linking with linking_clang.so
base_program new
base_program delete
linking new
linking delete


How do I get the clang++ behaviour in g++?


Viewing all articles
Browse latest Browse all 22113

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>