Try-catch doesn't work in shared library?

前端 未结 2 1713
太阳男子
太阳男子 2021-02-06 13:23

(This is like my other question but this one is for another thing, even if it\'s related)

I\'ve got a big issue in my project. I\'ve got a library which handl

相关标签:
2条回答
  • 2021-02-06 13:47

    According to gcc manual:

    if a library or main executable is supposed to throw or catch exceptions, you must link it using the G++ or GCJ driver, as appropriate for the languages used in the program, or using the option -shared-libgcc, such that it is linked with the shared libgcc.

    Shared libraries (in C++ and Java) have that flag set by default, but not main executables. In any case, you should use it on both.

    Test Case:

    lib.cpp:

    #include "lib.hpp"
    #include <string>
    #include <iostream>
    
    using namespace std;
    
    int function_throws_int() {
        try {
            throw 2;
        }
        catch (...) {
            cout << "int throws lib" << endl;
            throw;
        }
    
        return -1;
    }
    
    int function_throws_string() {
        try {
            throw std::string("throw");
        }
        catch (...) {
            cout << "throws string lib" << endl;
            throw;
        }
    }
    

    lib.hpp:

    int function_throws_int();
    int function_throws_string();
    

    Compile command line: g++ -m64 -g -shared-libgcc -shared -fPIC -std=c++11 -o libtest.so lib.cpp

    main.cpp:

    #include "lib.hpp"
    #include <string>
    #include <iostream>
    
    using namespace std;
    
    int main(int argc, char ** argv) {
        try {
            function_throws_int();
        }
        catch (const string & e) {
            cout << "string caught main" << endl;
        }
        catch (int i) {
            cout << "int caught main" << endl;
        }
    
        return 0;
    }
    

    Compile command line: g++ -m64 -g -shared-libgcc -o main -L. main.cpp -ltest

    Execute: LD_LIBRARY_PATH=. ./main

    Output:

    int throws lib
    int caught main
    
    0 讨论(0)
  • 2021-02-06 14:03

    Simple. Never use ld with C++. I changed all ld commands in my project to g++ but seems I forgot for this library.

    In short, I was using ld for building my library but g++ for the main executable. So the exceptions worked in the executable but not in the library because ld does not includes the C++ libraries which handle the exception system.

    0 讨论(0)
提交回复
热议问题