0

I have the CMakeLists.txt for building tests using g++:

file(GLOB sources *.cpp)
foreach(src ${sources})
    get_filename_component(src ${src} NAME_WE)
    string(REPLACE "our_prefix" "" bin ${src})
    add_executable(${bin} ${src})
    target_link_libraries(${bin} our options go here) 
endforeach()

What I need to do is to add the option -nodefaultlibs to each test. I've tried to do it like this:

file(GLOB sources *.cpp)
foreach(src ${sources})
    get_filename_component(src ${src} NAME_WE)
    string(REPLACE "our_prefix" "" bin ${src})
    add_executable(${bin} ${src})
    set_target_properties(${bin} PROPERTIES 
        INTERFACE_COMPILE_OPTIONS "-nodefaultlibs"
    )
    target_link_libraries(${bin} our options go here) 
endforeach()

But it seems to have no effect. I've also tried to use the command target_compile_options instead of set_target_properties - and it also had no effect.

Cmake generates the link.txt file for each test - I suppose this file describes the building command used for the test. This file doesn't contain my option -nodefaultlibs.

Could you please explain me what is the right way to add the -nodefaultlibs option?

Alexey
  • 710
  • 3
  • 7
  • 19
  • 2
    The option `-nodefaultlibs` is for the **linker**, not for the *compiler*. So you need to add it as a link option, via `target_link_libraries`, `CMAKE_EXE_LINKER_FLAGS` or `add_link_options` (available since CMake 3.13). – Tsyvarev Dec 24 '18 at 12:10
  • I've tested the option -nodefaultlibs like this: g++ -nodefaultlibs - I suppose this command sends the -nodefaultlib to the compiler, and the compiler sends it further to the linker. – Alexey Dec 24 '18 at 12:46
  • I need to support cmake versions starting from 3.2. So I can't resort to the CMake 3.13 – Alexey Dec 24 '18 at 12:49
  • 1
    CMake **separates** compilation and linking steps. So the compiler cannot transfer anything to the linker. And for each option you should clearly understand, whether it is for the compiler, or for the linker (or for both of them). – Tsyvarev Dec 24 '18 at 14:43
  • 1
    Possible duplicate of [How do I add a linker or compile flag in a CMake file?](https://stackoverflow.com/questions/11783932/how-do-i-add-a-linker-or-compile-flag-in-a-cmake-file) – Tsyvarev Dec 24 '18 at 20:03

1 Answers1

1

-nodefaultlibs is a linker flag so use set_target_properties(${bin} PROPERTIES LINK_OPTIONS -nodefaultlibs) or target_link_libraries(${bin} PRIVATE -nodefaultlibs) or for CMake 3.2 set_target_properties(${bin} PROPERTIES LINK_FLAGS -nodefaultlibs).

INTERFACE_COMPILE_OPTIONS is used for something else and target_compile_options won't show up on the link line.

The link.txt file isn't always generated. When using MSYS Makefiles the linker flags show up in linklibs.rsp.

fdk1342
  • 3,274
  • 1
  • 16
  • 17