为什么 GCC --gc-sections 和 -ffunction-sections 不起作用? (构建)

Why GCC --gc-sections and -ffunction-sections is not working? (cmake build)

我想知道为什么 GCC 编译器标志 -ffunction-sections 和链接器标志 --gc-sections 不消除不必要的 resp。我的最终可执行文件中未引用 symbols/functions 代码。 为什么它没有像 GCC 文档中预期和描述的那样工作?

可能是我监督了一些无意的引用!?
检查已经使用这个非常好的方法: GCC --gc-sections and finding symbol dependencies 在链接描述文件中使用 /DISCARD/。没有成功。没有引用我未使用的函数。

没有机会自动消除死代码!?为什么???

答案很简单(就我而言):

我正在使用 CMake 构建我的项目,它正在插入标志 -rdynamic !
据我所知,-rdynamic--gc-sections 选项的组合在 GCC 文档的任何地方都没有提到。 应该有这样的警告:
-rdynamic 呈现 --gc-sections 无用的 bcs。所有符号都被隐式引用。

另请参阅:

当然只有CMake用户受此影响...(不知道):

CMP0065

Do not add flags to export symbols from executables without the :prop_tgt:ENABLE_EXPORTS target property.

CMake 3.3 and below, for historical reasons, always linked executables on some platforms with flags like -rdynamic to export symbols from the executables for use by any plugins they may load via dlopen. CMake 3.4 and above prefer to do this only for executables that are explicitly marked with the :prop_tgt:ENABLE_EXPORTS target property.

The OLD behavior of this policy is to always use the additional link flags when linking executables regardless of the value of the :prop_tgt:ENABLE_EXPORTS target property.

The NEW behavior of this policy is to only use the additional link flags when linking executables if the :prop_tgt:ENABLE_EXPORTS target property is set to True.

This policy was introduced in CMake version 3.4. Unlike most policies, CMake version |release| does not warn by default when this policy is not set and simply uses OLD behavior. See documentation of the :variable:CMAKE_POLICY_WARNING_CMP0065 <CMAKE_POLICY_WARNING_CMP<NNNN>> variable to control the warning.

要删除大部分不必要的 -rdynamic CMakeLists.txt 只需添加 cmake_policy(SET CMP0065 NEW)