【发布时间】: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();
}
我想要两个独立的程序:
main_run
gcc another_main.c foo_bar_run.c -o main_run && ./main_run
bar
foo
main_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 是的,因为如果
A和B是 C++ 类或命名空间,这完全是一个不同的问题。
标签: c weak-references stubbing