'CMake: custom add_executable failing when adding link libraries

I'm making a custom cross-platform library that needs to be in native gui mode, so, the add_executable need to have the parameter of WIN32 or MACOSX_BUNDLE depending on the platform. To facilitate this process I created a cmake function:

function(add_windowed_executable targetProject targetSources)
    if (CMAKE_SYSTEM_NAME STREQUAL "Windows")
        add_executable(${targetProject} WIN32 ${targetSources})
    elseif(CMAKE_SYSTEM_NAME STREQUAL "Darwin") # MacOS
        add_executable(${targetProject} MACOSX_BUNDLE ${targetSources})
        # ... link with native libraries
    elseif(CMAKE_SYSTEM_NAME STREQUAL Linux)
        add_executable(${targetProject} ${targetSources})
        # ... link with native libraries
    endif()
endfunction()

Now when I try to create an executable with target_link_library it gives me the error "Cannot specify link libraries for target "test" which is not built by this project.". It comes down to the fact that the add_windowed_executable is the one that calls the add_executable and not the main file. Is there any way to use this function and allow to link with other libraries, basically replicating the add_executable command?

Main cmake

# ...

add_subdirectory("functions")

# ...

add_windowed_executable("test" "src/main.c")
target_link_libraries("test" "otherLibrary") # It's here where the error appears

EDIT: tryed with macro instead of function and the error still remains



Solution 1:[1]

 add_executable(targetProject

You added targetProject. Not test. You want to use the variable:

add_executable(${targetProject} ${targetSources})

and the same with targetSources.

Solution 2:[2]

It needs to be done the oposite way. First check the os then create the function or macro:

if (CMAKE_SYSTEM_NAME STREQUAL "Windows")
    function(add_windowed_executable targetProject)
        add_executable(${targetProject} WIN32 ${ARGN})
    endfunction()
# ...
endif ()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 KamilCuk
Solution 2 Rui Pedro