Linux CMake Linker Flags

Does anyone know how to get CMake to add linker flags?

Previously I would call make like this:
make CONFIG=Release TARGET_ARCH="-latomic -m64"

But I don’t know where to add this info in CMake.
I’ve tried adding this at the bottom of the CMakeLists.txt file but it doesn’t seem to modify the generated makefile at all…

if (LINUX)
    target_link_libraries(${CMAKE_PROJECT_NAME} PRIVATE "-latomic -m64")
endif()

Any ideas?

LINUX is not a standard CMake variable. If you are defining it yourself, make sure that it is defined to what you expect.

Then, you can’t pass -latomic -m64 as a single string, since that will be interpreted as attempting to link against a library named atomic -m64.

If you’re using CMake 3.13 or later, you should prefer target_link_options for non-library linker flags.

To sum up, something like this should work:

if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
  target_link_libraries(<target> PRIVATE "-latomic")
  target_link_options(<target> PRIVATE "-m64")
endif()

(though not tested)

2 Likes

Thanks so much, that worked! :raised_hands:

I guess that’s what I get from too much Stack Overflow.
Is there a reliable Linux CMake variable? I use if (MSVC) and if (APPLE) but now I’m wondering if those aren’t actually being called either :man_facepalming:

There is only CMAKE_SYSTEM_NAME STREQUAL "Linux".

MSVC and APPLE are standard CMake variables, but you might want to double check what they mean. For instance, MSVC doesn’t mean “Windows”, since you could be using Clang or MinGW. And APPLE means all Apple platforms, not just macOS.

1 Like

This is why I switched to if (WIN32) since moving to clang-cl to compile my Windows build. WIN32 is a standard CMake variable as well, right?

Yes it is. You can find all variables that describe the system here: cmake-variables(7) — CMake 3.28.0-rc5 Documentation

1 Like

Great, thanks for that link. I’ve got it working now!