Skip to content

Add thread_local only when CATCH_CONFIG_EXPERIMENTAL_THREAD_SAFE_ASSERTIONS is defined #3044

@stk-ableton

Description

@stk-ableton

Our use case is maybe a little uncommon: we are building Catch2 as a DLL (using a local patch that adds the necessary __declspec(dllexport) annotations). On Windows, thread_local is incompatible with building DLLs, and results in error C2492 ("data with thread storage duration may not have dll interface").

Since we are already patching Catch, it's easy to add another patch that removes the thread_local again, and because we are not opting in to CATCH_CONFIG_EXPERIMENTAL_THREAD_SAFE_ASSERTIONS, this seems like a safe change. But it would be nice if we didn't have to do that. I'm thinking of a change similar to this (obviously incomplete):

diff --git a/src/catch2/internal/catch_message_info.cpp b/src/catch2/internal/catch_message_info.cpp
index bc887abf..732c36e8 100644
--- a/src/catch2/internal/catch_message_info.cpp
+++ b/src/catch2/internal/catch_message_info.cpp
@@ -21,6 +21,6 @@ namespace Catch {
 
     // Messages are owned by their individual threads, so the counter should be thread-local as well.
     // Alternative consideration: atomic, so threads don't share IDs and things are easier to debug.
-    thread_local unsigned int MessageInfo::globalCount = 0;
+    CATCH_THREAD_LOCAL unsigned int MessageInfo::globalCount = 0;
 
 } // end namespace Catch
diff --git a/src/catch2/internal/catch_message_info.hpp b/src/catch2/internal/catch_message_info.hpp
index 7597f80d..bb8b2b81 100644
--- a/src/catch2/internal/catch_message_info.hpp
+++ b/src/catch2/internal/catch_message_info.hpp
@@ -38,7 +38,7 @@ namespace Catch {
             return sequence < other.sequence;
         }
     private:
-        static thread_local unsigned int globalCount;
+        static CATCH_THREAD_LOCAL unsigned int globalCount;
     };
 
 } // end namespace Catch
diff --git a/src/catch2/internal/catch_thread_support.hpp b/src/catch2/internal/catch_thread_support.hpp
index c15980b7..beec711c 100644
--- a/src/catch2/internal/catch_thread_support.hpp
+++ b/src/catch2/internal/catch_thread_support.hpp
@@ -13,6 +13,10 @@
 #if defined( CATCH_CONFIG_EXPERIMENTAL_THREAD_SAFE_ASSERTIONS )
 #    include <atomic>
 #    include <mutex>
+
+#    define CATCH_THREAD_LOCAL thread_local
+#else
+#    define CATCH_THREAD_LOCAL
 #endif
 
 #include <catch2/catch_totals.hpp>

Any thoughts?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions