Search code examples
c++c++11gccatomicstdatomic

Atomic objects of trivially copyable types in GCC


According to the C++ standard, std::atomic can be combined with any trivially copyable type. However, GCC produces the following error messages:

#include <atomic>
struct TriviallyCopyableType {
  int a, b, c, d;
};
int main() {
  std::atomic<TriviallyCopyableType> a;
  a.store({});      // undefined reference to `__atomic_store_16'
  a.is_lock_free(); // undefined reference to `__atomic_is_lock_free'
}

Clang and Microsoft's compiler do not complain. Am I doing something wrong? Is this a known problem? After all, atomic operations were implemented years ago in GCC 4.4. Are there any workarounds other than using a different compiler? Since Clang implements std::atomic<TriviallyCopyableType> even lock-free, I do not want to use explicit locking.


Solution

  • This answer is compiled from the comments.

    You need to explicitly link the atomic operations library with your program by specifying -latomic on the command line.

    -mcx16 may enable lock-free atomic operations on 128-bit data types.