Pendyala
Pendyala

Reputation: 655

what exactly happens when I compile instruction __atomic_add_fetch

I have a instruction in my code calling function __atomic_add_fetch. When I compile this code, I am getting compilation error as below

error: undefined reference to '__atomic_fetch_add_8'

I really could not understand why it is throwing undefined reference to __atomic_fetch_add_8 when I am calling __atomic_add_fetch. Could somebody please help me understand what exactly happening while compiling this code?

Note: I am specifically looking to understand "what is internally happening that translates __atomic_add_fetch into __atomic_fetch_add_8". Not the solution to fix compilation issue.

Upvotes: 2

Views: 3822

Answers (1)

Petr Skocik
Petr Skocik

Reputation: 60058

You should be using the standardized atomic_fetch_add.

In any case, it looks like your __atomic_fetch_add with the given argument type (presumably an 8-byte integer) cannot be resolved to an assembly instruction(s) on your platform so it is getting resolved to a function call for which you'll need to link libatomic (-latomic).

Edit with details:

On gcc, __atomic_fetch_add appears to be the compiler built in used to implement stdatomic.h's atomic_fetch_and_explicit (which is just a simple macro name for it). As I've noted, you should really be using the standard name atomic_fetch_add_explicit, not the nonportable implementation detail that __atomic_fetch_add is.

Regardless, the issue seems to be that gcc and clang don't implement atomic_fetch_and_explicit with instructions on ARM (unlike on ARM64 or x86-64) but instead they generate a call to a (global-lock-using) function from the libatomic library. The name of the function seems to be derived from the number of bytes in the integer you're trying to fetch_add to (__atomic_fetch_add_8 if you're fetch_adding to _Atomic uin64_t __atomic_fetch_add_4 if you're fetch_adding to _Atomic uin32_t, etc.).

https://gcc.godbolt.org/z/S67g7b

Upvotes: 8

Related Questions