link libatomic on systems without adequate builtin atomics

diff --git a/cmake/CMakeLists.txt b/cmake/CMakeLists.txt
index 71a0f37..0484e36 100644
--- a/cmake/CMakeLists.txt
+++ b/cmake/CMakeLists.txt
@@ -132,6 +132,22 @@
   add_definitions(-DHAVE_ZLIB)
 endif (HAVE_ZLIB)
 
+# We need to link with libatomic on systems that do not have builtin atomics, or
+# don't have builtin support for 8 byte atomics
+set(protobuf_LINK_LIBATOMIC false)
+if (NOT MSVC)
+  include(CheckCXXSourceCompiles)
+  check_cxx_source_compiles("
+    #include <atomic>
+    int main() {
+      return std::atomic<int64_t>{};
+    }
+  " protobuf_HAVE_BUILTIN_ATOMICS)
+  if (NOT protobuf_HAVE_BUILTIN_ATOMICS)
+    set(protobuf_LINK_LIBATOMIC true)
+  endif (NOT protobuf_HAVE_BUILTIN_ATOMICS)
+endif (NOT MSVC)
+
 if (protobuf_BUILD_SHARED_LIBS)
   set(protobuf_SHARED_OR_STATIC "SHARED")
 else (protobuf_BUILD_SHARED_LIBS)
diff --git a/cmake/libprotobuf-lite.cmake b/cmake/libprotobuf-lite.cmake
index c06cf96..39c39c1 100644
--- a/cmake/libprotobuf-lite.cmake
+++ b/cmake/libprotobuf-lite.cmake
@@ -64,6 +64,9 @@
 add_library(libprotobuf-lite ${protobuf_SHARED_OR_STATIC}
   ${libprotobuf_lite_files} ${libprotobuf_lite_includes} ${libprotobuf_lite_rc_files})
 target_link_libraries(libprotobuf-lite ${CMAKE_THREAD_LIBS_INIT})
+if(protobuf_LINK_LIBATOMIC)
+  target_link_libraries(libprotobuf-lite atomic)
+endif()
 target_include_directories(libprotobuf-lite PUBLIC ${protobuf_source_dir}/src)
 if(MSVC AND protobuf_BUILD_SHARED_LIBS)
   target_compile_definitions(libprotobuf-lite
diff --git a/cmake/libprotobuf.cmake b/cmake/libprotobuf.cmake
index fd70da7..710b34c 100644
--- a/cmake/libprotobuf.cmake
+++ b/cmake/libprotobuf.cmake
@@ -118,7 +118,10 @@
   ${libprotobuf_lite_files} ${libprotobuf_files} ${libprotobuf_includes} ${libprotobuf_rc_files})
 target_link_libraries(libprotobuf ${CMAKE_THREAD_LIBS_INIT})
 if(protobuf_WITH_ZLIB)
-    target_link_libraries(libprotobuf ${ZLIB_LIBRARIES})
+  target_link_libraries(libprotobuf ${ZLIB_LIBRARIES})
+endif()
+if(protobuf_LINK_LIBATOMIC)
+  target_link_libraries(libprotobuf atomic)
 endif()
 target_include_directories(libprotobuf PUBLIC ${protobuf_source_dir}/src)
 if(MSVC AND protobuf_BUILD_SHARED_LIBS)