【问题标题】:Stubbing: is it possible to use something like the opposite of __attribute__((weak))?存根:是否可以使用与 __attribute__((weak)) 相反的东西?
【发布时间】:2021-12-05 13:59:10
【问题描述】:

让我们假设以下 C 代码:

foo_bar_run.c

#include "foo_bar_run.h"

int __attribute__((weak)) foo() 
{
    printf("foo\n");
}

int bar()
{
    printf("bar\n");
    foo();
}

foo_bar_run.h

#include <stdio.h>

extern int __attribute__((weak)) foo() ;
extern int bar();

another_main.c

#include "foo_bar_run.h"

int main(void)
{
    bar();
}

bar_test.c

#include <stdio.h>
#include "foo_bar_run.h"

int foo()
{
    printf("stubbed foo\n");
}

int main(void)
{
    bar();
}

我想要两个独立的程序:

ma​​in_run

gcc another_main.c foo_bar_run.c -o main_run && ./main_run
bar
foo

ma​​in_test

gcc bar_test.c foo_bar_run.c -o main_test && ./main_test 
bar
stubbed foo

是否有更优雅的解决方案不包括更改 foo_bar_run 原型? (它将保持int foo()

类似于使用__attribute__(strong) 定义 bar_test.c/foo() 或不使用任何 __attribute__ 关键字的东西。

【问题讨论】:

  • C 还是 C++?您标记了这个 C,但使用了 C++ 语法。
  • 无论如何,听起来像一个普通的“模拟”宏会起作用吗?在 B.c 做#define foo another_foo.
  • @Lundin - C++ 中没有任何内容允许通过文件名来限定标识符。不陷入语言战争就很难理解修辞手法吗?
  • @StoryTeller-UnslanderMonica 是的,因为如果 AB 是 C++ 类或命名空间,这完全是一个不同的问题。

标签: c weak-references stubbing


【解决方案1】:

__attribute__((weak)) 不是函数类型或存储类的一部分,不需要出现在头文件声明中。它是一个 GNU C 扩展,与弱符号有关,弱符号是一个链接概念。不必在编译时将符号声明到使用该符号的地方。只要它是一个外部符号就足够了。当程序链接在一起时,弱点与如何在面对多个定义时解决外部引用的灵活性有关。

您尝试解决的问题不需要弱符号,因为您可以控制所有符号定义以及程序如何划分为.o 目标文件以及哪些目标文件进入哪些可执行文件。在您的代码和构建结构中,您可以安排每个程序与任何foobar 函数的单个定义链接。

弱符号有助于处理共享库的部署和维护中的某些问题。尤其是广泛使用的平台库。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-23
    • 2011-04-13
    • 1970-01-01
    相关资源
    最近更新 更多