How to link same set of libraries to multiple targets/executables in cmake? - cmake

I have multiple executable/target files in my project structure, and they all use the same libraries. Is there a way to make this more compact? Perhaps something like a for-loop?
set(ALL_LIBS lib1 lib2 lib3) # etc.
add_executable(program1 program1.cpp)
target_link_libraries(program1 PRIVATE ${ALL_LIBS})
add_executable(program2 program2.cpp)
target_link_libraries(program2 PRIVATE ${ALL_LIBS})
add_executable(program3 program3.cpp)
target_link_libraries(program3 PRIVATE ${ALL_LIBS})
add_executable(program4 program4.cpp)
target_link_libraries(program4 PRIVATE ${ALL_LIBS})
I'm looking for a solution that achieves something similar or cleaner than this:
add_executable(program1 program1.cpp)
add_executable(program2 program2.cpp)
add_executable(program3 program3.cpp)
add_executable(program4 program4.cpp)
# somehow get list of target names
foreach(${TARGETS})
# link libraries to each target
target_link_libraries(${TARGET_NAME} PRIVATE ${ALL_LIBS})
endforeach()

You may define your own macro or function which defines an executable like normal add_executable but also links the executable with the common libraries.
set(ALL_LIBS lib1 lib2 lib3) # etc.
# A wrapper around add_executable which links all created executables with libraries
function(add_executable_common name)
# Forward all parameters to add_executable
add_executable(${ARGV})
# Perform additional actions
target_link_libraries(${name} PRIVATE ${ALL_LIBS})
endfunction()
# Created function can be used in the very same manner as add_executable.
add_executable_common(program1 program1.cpp)
add_executable_common(program2 program2.cpp)
add_executable_common(program3 program3.cpp)
add_executable_common(program4 program4.cpp)
CMake variables ARGV and ARGN provide a perfect way to forward parameters of one function/macro to another.
This allows to easily create wrappers to existed functions without needs to parse all parameters needed for the wrapped function.
E.g. while the function add_executable_common, defined above, doesn't parse parameters except the first one, it still can be used for define a STATIC or SHARED library and can be used for define a library with several sources:
add_executable_common(program5 SHARED program5.cpp additional_algos.cpp)

I found an okay solution to reduce line count. I just created a function to accept target name and file paths.
function(add_program_target TARGET_NAME)
add_executable(${TARGET_NAME} ${ARGN})
target_link_libraries(${TARGET_NAME} PRIVATE ${ALL_LIBS})
endfunction()
Then I just add targets like this:
add_program_target(program1 program1.cpp helper.cpp)
add_program_target(program2 program2.cpp)
add_program_target(program2 program3.cpp)
add_program_target(program2 program4.cpp)
# etc.

Related

How to include target include directories transitive through multiple linked libraries

we are working on an embedded project in C/C++ and currently some special needs appeared. Background is there are two compiled libraries which define the same symbols. The compiler allows to create relocatable output modules (with partial linking) and to hide symbols for other compilation units when linking. This also means the output module does not need to have all the symbols defined, this will be done in the final linking. Compiler used is TI LTS1.3.0. I will link directly to the relocatable-section of the manual: https://software-dl.ti.com/codegen/docs/tiarmclang/rel1_3_0_LTS/compiler_manual/linker_description/04_linker_options/linker-output-options.html#stdz0756429
The other part of the project is hardly built on CMake with static libraries which are linked against each other via target_link_libraries.
To get this working I created an "add_executable"-target for each of those both output modules with the same symbols. To those I pass the static-libraries by CMake and get the linked with target_link_libraries.
But now I have a problem. All contents of the static libraries are compiled in each of those output modules. This is unwanted behaviour since as said the final linking does the job of linking the missing stuff - so the static-libraries - to it. This should be done with another add_executable command via CMake as well.
using the target include directories property is not suitable since it only adds the include directories of the given target itself but not of the target the target will include and link against.
So e.g. if you have (pseudo code):
#library A
function( create_libA )
add_library( libA src/A.c )
target_include_directories( libA PUBLIC /inc ) #contains A.h
endfunction()
#library B. different location
function( create_libB LIBA )
add_library( libB src/B.c )
target_link_libraries( libB PUBLIC ${LIBA} )
target_include_directories( libB PUBLIC /inc ) #contains B.h
endfunction()
#target output module with partial linking. Only should link and compile LIBTOBELINKEDIN, not libB. different location.
function( build_part_module LIBB LIBTOBELINKEDIN )
add_executable( outputModuleA src/func.c ) #func.c does include A.h
#following would cause libA and libB also to be compiled and linked in the output due to transitive stuff as I understood, which is unwanted.
target_link_libraries( outputModuleA PUBLIC ${LIBB} ${LIBTOBELINKEDIN} )
#trying this
get_target_property(libBInc ${LIBB} INTERFACE_INCLUDE_DIRECTORIES)
#will only include B.h but not A.h. compilation will fail.
target_include_directories(outputModuleA /inc ${libBInc})
I did not find any solution in Cmake itself to solve this problem. It's confusing me since all the include-directories must be known when the libraries are passed transitive, which is stated in the documentation. But I understand that getting the target include directories of just the passed lib does not include the other ones.
Since target_link_libraries does also not work this way I can only think of a maybe recursive solution? But for that my knowledge is just non-existent.
target_link_libraries with something like HEADERS_ONLY would be helpfull for this job.
Also one can say: if the output module contains all the definitions it won't be a problem, since the linker then knows them and will do its magic.
But this is also unwanted, since we use the generated static-libraries to place them into sections in different regions of the RAM directly. This would then mean to create another linker-script for partial linking which defines sections which then can be again moved. But the more we go this direction, the less we need CMake for it.
Instead of get_target_property use $<TARGET_PROPERTY> generator expression: the property's value, extracted by that expression, already includes transitive propagation:
target_include_directories(outputModuleA PRIVATE
$<TARGET_PROPERTY:libB,INTERFACE_INCLUDE_DIRECTORIES>
)
Note, that generator expressions has limited usage: not all functions expects them. Documentation for target_include_directories clearly states that the command supports generator expressions.

Cmake generator for all executables

I have several executables:
add_executable(exe1 ${DRIVERS_DIR}/exe1.cpp)
add_executable(exe2 ${DRIVERS_DIR}/exe2.cpp)
add_executable(exe3 ${DRIVERS_DIR}/exe3.cpp)
And I need to add a link library to all of them:
target_link_libraries(exe1 ${LIB_NAME})
target_link_libraries(exe2 ${LIB_NAME})
target_link_libraries(exe3 ${LIB_NAME})
How can I replace three target_link_libraries with a single one with generator expression for exe1, exe2, exe3 ?
with generator expression for exe1, exe2, exe3?
You cannot use a generator expression in the target argument of target_link_libraries, period. It simply is impossible.
How can I replace three target_link_libraries with a single one[?]
You can use a loop:
set(exes exe1 exe2 exe3)
foreach (exe IN LISTS exes)
add_executable("${exe}" "${DRIVERS_DIR}/${exe}.cpp")
target_link_libraries("${exe}" PRIVATE "${LIB_NAME}")
endforeach ()
This looks pretty clean to me.
You cannot use generator expressions here.
It's pretty simple to create a function for creating the executable and linking it though:
#[===[
Usage:
my_create_linked_exe(target source...)
]===]
function(my_create_linked_exe TARGET SRC)
add_executable(${TARGET} ${SRC} ${ARGN})
target_link_libraries(${TARGET} PRIVATE ${LIB_NAME})
endfunction()
my_create_linked_exe(exe1 ${DRIVERS_DIR}/exe1.cpp)
my_create_linked_exe(exe2 ${DRIVERS_DIR}/exe2.cpp)
# helper.cpp only added to demonstrate you could pass more than a single parameter
my_create_linked_exe(exe3 ${DRIVERS_DIR}/exe3.cpp ${DRIVERS_DIR}/helper.cpp)

is it possible to make target shared library file name variable according to environment variable in cmake?

I'm not familar with cmake but in CMakeLists.txt we set the target shared library name like this.
add_library( mylib SHARED ${source_list} )
This generates libmylib.so and other settings in CMakeLists.txt are defined for mylib like
about the mylib
and also we can use shell environment variable to do some selective settings like
target_compile_definitions( mylib PRIVATE -DQQQ -D... )
Also it is possible to use shell environment variable to do some selective things.
if(defined env{MYVAR})
set(CMAKE_C_FLAGS "-g -DXYZ")
else()
set(CMAKE_C_FLAGS "-DXYZ")
endif()
I would be happy if I could set the target shared library name as a variable according to the environment variable and use that selected name variable as the shared library name in all other settings. In other words, is it possible to do things like below?
if (defined ENV{FOR_QEMU})
set_name(target_name "simlib_qemu")
else ()
set_name(target_name "simlib")
endif ()
add_library(target_name SHARED ${source_list} )
target_compile_definitions( target_name PRIVATE -DQQQ -D... )
...
You can set the output name of a target to anything you like via:
set_target_properties(target_name PROPERTIES OUTPUT_NAME "whatever")
Then instead of libtarget_name.so, you'll get libwhatever.so. You would continue to refer to the target as target_name in your CMakeLists.txt.
However, since this will only work during configure time anyway, I strongly urge you to use a normal CMake variable instead. You may initialize it from the environment if it is not set, like so:
option(FOR_QEMU "Enable if building with Qemu support" "$ENV{FOR_QEMU}")
add_library(simlib SHARED ${source_list})
target_compile_definitions(simlib PRIVATE -DQQQ -D...)
if (FOR_QEMU)
set_target_properties(target_name PROPERTIES OUTPUT_NAME "simlib_qemu")
endif ()
This way, the CMake variable FOR_QEMU is the de-facto control and it is initialized on the first execution if the matching env-var is set. It will also appear with documentation in the cache, so other developers may query the build system directly for all its configuration points. Bear in mind: CMake is not Make and reading from the environment on every configure is a surprising behavior and generally bad practice.

target type depending generic rule

My project contains a lot of libraries and executables. On Windows a .rc file is used to embed meta informations (version, original file name, ...). One of these meta informations is FILETYPE (VFT_DLL, VFT_APP). So I add a -D TYPE definition to the resource compiler (which I evaluate inside the .rc) to distinguish between dll/exe.
Example:
add_library (myLib SHARED "src/myLib.cpp"
"src/myLib.rc")
target_include_directories (myLib PUBLIC "include")
set_source_files_properties("src/myLib.rc" APPEND_STRING PROPERTY COMPILE_FLAGS "-DDLL")
I won't repeat myself in dozens of CMakeLists, is there a possibility to create a generic rule (e.g. in a .cmake include) that .rc files will be compiled with a target depending flag (-DDLL in case of SHARED library)?
I would write a small wrapper function:
# Or maybe not object, depending on what you want
add_library(rc_for_shared OBJECT src/myLib.rc)
target_compile_definitions(rc_for_shared PRIVATE -DDLL)
add_library(rc_for_executable OBJECT src/myLib.rc)
# This is a draft from my memory
function(target_add_the_rc_file target)
get_target_properties(target PROPERTIES TYPE type)
if (type STREQUAL "SHARED")
target_link_libraries(${target} rc_for_shared)
# or maybe target_source(${target} $<TARGET_OBJECTS:rc_for_shared>)
# depending on what you want
elseif(type STREQUAL "EXECUTABLE")
target_link_libraries(${target} rc_for_executable)
endif()
endfunction()
then you would:
add_library(myLib SHARED src/myLib.cpp)
target_include_directories(myLib PUBLIC)
target_add_the_rc_file(myLib)

target_compile_definitions for multiple CMake targets?

I've been told it's bad practice to do things like seting CFLAGS directly in CMake, and that, instead, I should use the target_compile_definitions() command.
Ok, but - what if I want to use similar/identical definitions for multiple (independent) targets? I don't want to repeat myself over and over again.
I see three possible ways:
The preferred one using target_compile_definitions(... INTERFACE/PUBLIC ...) which would self-propagate the compiler definitions to targets depending on it via target_link_libraries() command.
Using the set_property(TARGET target1 target2 ... APPEND PROPERTY COMPILE_DEFINITIONS ...) to set the same definitions to multiple targets.
You may still use the "old commands" of add_definitions() and remove_definitions() to modify COMPILE_DEFINITIONS directory property (which would pre-set all COMPILE_DEFINITIONS target properties in this directories scope).
References
Is Cmake set variable recursive?
CMake: Is there a difference between set_property(TARGET ...) and set_target_properties?
tl;dr: You can iterate the targets in a loop.
If you have a bunch of targets with some common/similar features, you may want to simply manipulate them all in a loop! Remember - CMake is not like GNU Make, it's a full-fledged scripting language (well, sort of). So you could write:
set(my_targets
foo
bar
baz)
foreach(TARGET ${my_targets})
add_executable(${TARGET} "${TARGET}.cu")
target_compile_options(${TARGET} PRIVATE "--some_option=some_value")
target_link_libraries(${TARGET} PRIVATE some_lib)
# and so on
set_target_properties(
${TARGET}
PROPERTIES
C_STANDARD 99
C_STANDARD_REQUIRED YES
C_EXTENSIONS NO )
endforeach(TARGET)
And you could also initialize an empty list of targets, then add to it here-and-there, and only finally apply your common options and settings to all of them, centrally.
Note: In this example I added PRIVATE compile options, but if you need some of them to propagate to targets using your targets, you can make them PUBLIC).
another neat solution is to define an interface library target (a fake target that does not produce any binaries) with all required properties and compiler definitions, then link the other existing targets against it
example:
add_library(myfakelib INTERFACE)
target_compile_definitions(myfakelib INTERFACE MY_NEEDED_DEFINITION)
add_executable(actualtarget1 main1.cpp)
add_executable(actualtarget2 main2.cpp)
set_property(
TARGET actualtarget1 actualtarget2
APPEND PROPERTY LINK_LIBRARIES myfakelib
)
refs:
https://cmake.org/cmake/help/latest/command/add_library.html#interface-libraries