使函数全局范围像编译器内在

making function global scope like a compiler intrinsic

我使用的函数是 arm 编译器固有的,但不是 GCC 固有的(即 arm 的 __strex)。我将 strex 函数用作内联函数的一部分。使用 arm 编译器它工作正常。我有两个项目,使用 arm 编译器的目标和使用 GCC 的测试项目。使用 GCC,我无法使用我尝试过的许多解决方法来编译它。我一直无法在范围内获取变量。由于函数是内联的,这意味着目标文件期望函数在该文件的范围内。我不想修改目标以包含仅供测试项目编译所需的头文件。有什么方法可以通过链接器或编译器 attribute/something 创建一个函数,它的行为很像一个在整个代码库中具有全局作用域的内部函数?

I don't want to modify the target [file] to include a header file which is only needed for the test project to compile.

您不需要修改它。使用 -include some/header/file.h GCC 标志 non-intrusively 包含一个额外的 header.

然后您可以创建函数 inline 并将其放入 header,或者在其他地方定义它。

需要 声明函数以便编译器能够内联它。如果出于某种原因您不想修改任何源代码,请修改您的构建以使用命令行选项进行编译。

一种可能性是像 -D__strex=something 这样的预处理器选项,如果您可以将其定义为 CPP 宏。

或者更有可能使用 GCC 的 -include foo.h option 来包含一个 .h,它提供了您需要的任何内在函数的正确定义。 (它默认搜索 #include "..." 路径,而不是 #include <...>)。

-include file

Process file as if "#include "file"" appeared as the first line of the primary source file. However, the first directory searched for file is the preprocessor's working directory instead of the directory containing the main source file. If not found there, it is searched for in the remainder of the "#include "..."" search chain as normal.


GCC 确实有一些指令的内部函数。不过,关于 LL/SC 指令的 IDK,例如 strex;这将是棘手的,因为你可以在 之间 ldrexstrex 之间放置什么而不总是失败。如果调试模式做了额外的 loads/stores.

例如https://github.com/ARMmbed/core-util/issues/76 suggests that project move away from those intrinsics and use GNU C __atomic builtins. Consider doing the same yourself, e.g. using __atomic_add_fetch instead of manual __ldrex and __strex. https://gcc.gnu.org/onlinedocs/gcc/_005f_005fatomic-Builtins.html