Skip to content

linker: ld: toolchain_linker_finalize duplicates <LINKER_FLAGS> leading to link issues in some situations #82281

@axelnxp

Description

@axelnxp

Describe the bug

toolchain_linker_finalize was introduced by PR #78320 and according to its implementation for LD, it duplicates <LINKER_FLAGS>.
This is not a huge problem for common flags, but we got an issue when using --whole-archive xxx --no-whole-archive.
When this flag is duplicated, the linker exits with a duplicate definition error.
We've faced this issue in the connectedhomeip environment when migrating to 4.0 release.

cc @tejlmand

To Reproduce
Use the following cmake instruction:

target_link_options(${target} INTERFACE -Wl,--whole-archive <some static lib> -Wl,--no-whole-archive

This flag will be duplicated in the link command, leading to duplicate definitions.

Expected behavior
Link flags added with target_link_options should be unique.

Impact
We can currently workaround by bypassing the target_link_options and manually link the symbols we want, but this is not acceptable in the long run.

Logs and console output
I printed the content of CMAKE_CXX_LINK_EXECUTABLE before and after toolchain_link_options is called:

-- CMAKE_CXX_LINK_EXECUTABLE: <CMAKE_CXX_COMPILER> <FLAGS> <CMAKE_CXX_LINK_FLAGS> <LINK_FLAGS> <OBJECTS> -o <TARGET> <LINK_LIBRARIES>
-- CMAKE_CXX_LINK_EXECUTABLE: <CMAKE_CXX_COMPILER> <FLAGS> <CMAKE_CXX_LINK_FLAGS> <LINK_FLAGS> <LINK_FLAGS> <OBJECTS> -o <TARGET> <LINK_LIBRARIES> -L"/opt/zephyr-sdk-0.16.8/arm-zephyr-eabi/bin/../lib/gcc/arm-zephyr-eabi/12.2.0/thumb/v8-m.main+fp/hard" -lstdc++ -lm -lc -lgcc -lc

We can see <LINK_FLAGS> is duplicated by the function

Environment (please complete the following information):

  • OS: Linux
  • Toolchain: Zephyr SDK
  • Commit SHA or Version used: 2e3873adde2386e0bc9acdbcdc8d389fdf4b9aee

Additional context

Proposed patch:

diff --git a/cmake/linker/ld/target.cmake b/cmake/linker/ld/target.cmake
index 5e0a117c014..f9cdc938f54 100644
--- a/cmake/linker/ld/target.cmake
+++ b/cmake/linker/ld/target.cmake
@@ -148,7 +148,7 @@ macro(toolchain_linker_finalize)
   string(REPLACE ";" " " zephyr_std_libs "${zephyr_std_libs}")
 
   set(link_libraries "<LINK_FLAGS> <OBJECTS> -o <TARGET> <LINK_LIBRARIES> ${zephyr_std_libs}")
-  set(common_link "<LINK_FLAGS> ${link_libraries}")
+  set(common_link "${link_libraries}")
 
   set(CMAKE_ASM_LINK_EXECUTABLE "<CMAKE_ASM_COMPILER> <FLAGS> <CMAKE_ASM_LINK_FLAGS> ${common_link}")
   set(CMAKE_C_LINK_EXECUTABLE   "<CMAKE_C_COMPILER> <FLAGS> <CMAKE_C_LINK_FLAGS> ${common_link}")

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugThe issue is a bug, or the PR is fixing a bugpriority: mediumMedium impact/importance bug

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions