Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::uncaught_exception does not work across DLL boundaries

I have a class in a DLL with a destructor that checks for std::uncaught_exception(). If uses in a try/catch-block from an executable it does not says true if an exception is thrown.

Here is some example code: lib.h:

#pragma once

class __declspec(dllexport) C final
{
  public:
    ~C();
};

lib.cpp:

#include "lib.h"
#include <iostream>
#include <exception>

C::~C()
{
  std::cout << "C says: Uncaught: " << (std::uncaught_exception() ? "yes" : "no") << std::endl;
}

main.cpp:

#include "lib.h"
#include <iostream>
#include <exception>

class D final
{
  public:
    ~D()
    {
      std::cout << "D says: Uncaught: " << (std::uncaught_exception() ? "yes" : "no") << std::endl;
    }
};


int main(int argc, char **argv)
{
  try
  {
    C c;
    D d;
    throw 88;
  }
  catch (int a)
  {
    std::cout << "Code: " << a << std::endl;
  }
  {
    C c;
    D d;
  }
  return 0;
}

And build everything using:

cl.exe lib.cpp /EHsc /LD /c /Fo:lib.obj
link.exe lib.obj /incremental:no /fixed:no /DLL
cl.exe main.cpp /EHsc /LD /c /Fo:main.obj
link.exe main.obj /incremental:no /fixed:no lib.lib

On Visual Studio 2015 and Visual Studio 2013 x64 and x86 I get the result:

D says: Uncaught: yes
C says: Uncaught: no
Code: 88
D says: Uncaught: no
C says: Uncaught: no

I would expect the second line to be

C says: Uncaught: yes

So the class in the DLL does not see that there is an exception caused stack unwinding causing it's destructor to be called. But the class directly located in the inner class sees it.

Are there any linker / compiler flags that make this work as expected?

like image 550
mmmmmmmm Avatar asked Apr 25 '26 21:04

mmmmmmmm


1 Answers

Use /MD the dynamic runtime compiler option.

Without one, the main executable and each DLL all have their very own copy of the runtime, with all its internal state replicated for each module.

like image 107
n. 1.8e9-where's-my-share m. Avatar answered Apr 27 '26 10:04

n. 1.8e9-where's-my-share m.