Conditional linker flag

Hi,

I’m a noob.
I’m trying to pass a specific flag to the linker ONLY if the compiler is GCC 7 or below.

Here is my project structure:

├── CMakeLists.txt
└── src
├── CMakeLists.txt
├── main.cpp
└── project.h

The top level CMakeLists.txt contains

project(myproject)

if("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang")
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++17 -Wall -Wunused -g -O0")
    set(CMAKE_CXX_FLAGS_RELEASE  "${CMAKE_CXX_FLAGS_RELEASE} -DNDEBUG")
elseif(CMAKE_COMPILER_IS_GNUCXX)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++17 -Wall -Wunused -g -O0")
    set(CMAKE_CXX_FLAGS_RELEASE  "${CMAKE_CXX_FLAGS_RELEASE} -DNDEBUG")
endif()

add_subdirectory(src)

And the CMakeLists.txt file in the src folder contains

add_executable(myproject
    main.cpp
)

target_link_libraries(myproject curl)

install (TARGETS myproject DESTINATION bin)

The thing is, I’d like the linker options to contain the flag -lstdc++fs but only if the version of GCC that ends up being called is inferior to version 8.

For versions of GCC that are 8 and above the additional linker is not necessary.

I don’t control which version of the compiler will be used.

Is there a way to do this?

Thank you in advance

You can use a generator expressions to achieve this.

Also, prefer to manipulate targets instead of global variables.

Here’s how I would do it:

target_link_options (yourTarget PRIVATE $<$<AND:$<CXX_COMPILER_ID:GNU>,$<VERSION_LESS:$<CXX_COMPILER_VERSION>,8>>:-lstdc++fs>)

I think I’m misunderstanding: It appears to give an error:

cmake -DCMAKE_BUILD_TYPE=Debug -DCMAKE_VERBOSE_MAKEFILE=ON ..
-- The C compiler identification is GNU 7.5.0
-- The CXX compiler identification is GNU 7.5.0
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
CMake Error at CMakeLists.txt:15 (target_link_options):
  Unknown CMake command "target_link_options".


-- Configuring incomplete, errors occurred!
See also "/home/user/myproject/files/debug/CMakeFiles/CMakeOutput.log".

What version of CMake are you using?

cmake --version
cmake version 3.10.2

The target_link_options command was added in version 3.13.

Do you need to support older versions of CMake?

I don’t get to choose, it’s a Jenkins installation in this instance and I’m not sure I can upgrade anything
In fact, if I could upgrade, I’d update its gcc so it would be version 8 or higher and probably not have to add a special option for the linker.