From f55d2513181d60aeef46aab61fc8ebf50281a733 Mon Sep 17 00:00:00 2001 From: Robert Adam Date: Mon, 18 Jul 2022 07:48:28 +0200 Subject: [PATCH] Cpp: Link to threads library As detailed in #3708, it is necessary to link against the (p)threads library in order to be able to use std::call_once without producing linker errors. Since this function is frequently used in ANTLR's cpp version, this commit ensures that the respective library is always linked against in order to avoid this error, even if downstream users are not explicitly linking against an appropriate threads library. Fixes #3708 Signed-off-by: Robert Adam Co-authored-by: Bryan Tan --- runtime/Cpp/cmake/antlr4-runtime.cmake.in | 3 +++ runtime/Cpp/runtime/CMakeLists.txt | 7 +++++++ 2 files changed, 10 insertions(+) diff --git a/runtime/Cpp/cmake/antlr4-runtime.cmake.in b/runtime/Cpp/cmake/antlr4-runtime.cmake.in index 860aeb6012..697b36c628 100644 --- a/runtime/Cpp/cmake/antlr4-runtime.cmake.in +++ b/runtime/Cpp/cmake/antlr4-runtime.cmake.in @@ -5,6 +5,9 @@ set(ANTLR_VERSION @ANTLR_VERSION@) set_and_check(ANTLR4_INCLUDE_DIR "@PACKAGE_ANTLR4_INCLUDE_DIR@") set_and_check(ANTLR4_LIB_DIR "@PACKAGE_ANTLR4_LIB_DIR@") +include(CMakeFindDependencyMacro) +find_dependency(Threads) + include(${CMAKE_CURRENT_LIST_DIR}/@targets_export_name@.cmake) check_required_components(antlr) diff --git a/runtime/Cpp/runtime/CMakeLists.txt b/runtime/Cpp/runtime/CMakeLists.txt index bc487e1308..ac7c4f7a37 100644 --- a/runtime/Cpp/runtime/CMakeLists.txt +++ b/runtime/Cpp/runtime/CMakeLists.txt @@ -28,6 +28,13 @@ file(GLOB libantlrcpp_SRC add_library(antlr4_shared SHARED ${libantlrcpp_SRC}) add_library(antlr4_static STATIC ${libantlrcpp_SRC}) +# Make sure to link against threads (pthreads) library in order to be able to +# make use of std::call_once in the code without producing runtime errors +# (see also https://github.com/antlr/antlr4/issues/3708 and/or https://stackoverflow.com/q/51584960). +find_package(Threads REQUIRED) +target_link_libraries(antlr4_shared Threads::Threads) +target_link_libraries(antlr4_static Threads::Threads) + if (ANTLR_BUILD_CPP_TESTS) include(FetchContent)