link option wrong with -latomic

#include "thread"
#include "iostream"
#include "atomic"

using namespace std;

struct A { int a[100]; };
struct B { int x, y; };
int main()
{
    std::atomic<A> Ap ;
    std::atomic<B> Bp ;

    std::cout << std::boolalpha
              << "std::atomic<A> is lock free? "
              << Ap.is_lock_free() << '\n'
              << "std::atomic<B> is lock free? "
              << Bp.is_lock_free() << '\n';
    return 0;
}

when I compile it with gcc11 Ubuntu22.04 with makefile ,
it show me undefined reference to `__atomic_is_lock_free’.

So I use g++ main.cpp -latomic and it compile without error . great!!!

But what shoul I do if I want to add -latomic in cmake ? I try a lot of time…

Here is my cmake code


cmake_minimum_required(VERSION 3.20)

set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
set(CMAKE_CXX_STANDARD 17)

project(mlt)
add_executable(mlt main.cpp)

target_compile_options(mlt PUBLIC -latomic)
target_link_options(mlt PUBLIC -latomic)
#set(CMAKE_EXE_LINKER_FLAGS  -latomic )

Use target_link_libraries() command:

cmake_minimum_required(VERSION 3.20)

set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
set(CMAKE_CXX_STANDARD 17)

project(mlt)
add_executable(mlt main.cpp)

target_link_libraries(mlt PUBLIC atomic)

atomic should definitely be linked using PRIVATE (low level implementail detail of GCC)