CMake target_compile_options does not recognize a target when using CMAKE_TOOLCHAIN_FILE

I am trying to set different linker flags per target.

My setup is:

  • CMakeFiles.txt

  • cmakescripts/platform_ABC.cmake

  • cmakescripts/platform_XYZ.cmake

The CMakeFiles.txt defines two executables: targetA and targetB

The platform_xxxx.cmake file define the custom platform build / link settings.

How can I set two different setting for targetA and targetB in the platform_ABC.cmake?

The build command:

cmake . -DCMAKE_TOOLCHAIN_FILE="cmakescripts/platform_ABC.cmake"

Using the target_compile_options(targetA PUBLIC LD_FLAGS “-Wl,mapfile.txt”) will fail with error:

CMake Error at cmakescripts/platform_ABC.cmake:74 (targetA):
  Cannot specify compile definitions for target "targetA"
  which is not built by this project.

  • In CMake a toolchain script is executed when project command is called for the first time. At that time executable/library targets are not created yet. Moreover, it is not a purpose of a toolchain script to modify settings for a specific targets. Regular toolchain script just defines how executables and libraries should be compiled/link in general. However, a toolchain script may define some (custom) variables, which could be read by the project. Or it could call target-independent commands like add_link_options.

    – 




  • BTW, the command target_compile_options(targetA PUBLIC LD_FLAGS "-Wl,mapfile.txt") looks weird by itself: -W denotes a linker flag, but command target_compile_options is for compiler flags only.

    – 

Leave a Comment