Improve support for C11/atomic
Consider the following c11 code:
_Atomic(long long) ll;
int main(void)
{
++ll;
return 0;
}
If one use the following CMake code:
cmake_minimum_required(VERSION 3.13)
project(p)
add_executable(a a.c)
set_property(TARGET a PROPERTY C_STANDARD 11)
It will fails on some arch supported by Debian (armel, mipsel and powerpc) with something like this:
/usr/bin/ld: CMakeFiles/a.dir/a.c.o: in function `main':
a.c:(.text+0x54): undefined reference to `__atomic_fetch_add_8'
/usr/bin/ld: a.c:(.text+0x5c): undefined reference to `__atomic_fetch_add_8'
collect2: error: ld returned 1 exit status
Previous bug reports have been made in the past:
The basic idea is that cmake should not unconditionally add -latomic to GCC toolchain. However there is room for improvement to avoid boilerplate code in cmake listing.
It is not clear how it should be solved at this point.
- I see that this is solved for Android:
% grep -r latomic /usr/share/cmake-3.22/Modules
/usr/share/cmake-3.22/Modules/Platform/Android/ndk-stl-c++_static.cmake: string(APPEND CMAKE_${lang}_STANDARD_LIBRARIES " -latomic") # provided by toolchain
/usr/share/cmake-3.22/Modules/Platform/Android-Common.cmake: string(APPEND CMAKE_${lang}_STANDARD_LIBRARIES " -latomic -lm")
- Let's consider now std::thread (c++11) support in cmake. It is assumed that the programmer understand that std::thread on Linux is implemented using pthread. Thus for the following c++11 program:
#include <iostream>
#include <thread>
#include <mutex>
std::once_flag flag;
void simple_do_once()
{
std::call_once(flag, [](){ std::cout << "Hello, world!\n"; });
}
int main()
{
std::thread st1(simple_do_once);
st1.join();
return 0;
}
It is expected to write the following CMake code:
cmake_minimum_required(VERSION 3.13)
project(p)
set(CMAKE_THREAD_PREFER_PTHREAD TRUE)
set(THREADS_PREFER_PTHREAD_FLAG TRUE)
find_package(Threads REQUIRED)
add_executable(b b.cxx)
set_property(TARGET b PROPERTY CXX_STANDARD 11)
target_link_libraries(b Threads::Threads) # REQUIRED
What would be the best approach for CMake to provide -latomic :
- Add it to CMAKE_C_STANDARD_LIBRARIES ?
- Through a module:
find_package(Atomic REQUIRED)
?