【问题标题】:In C, is it possible to change exported function name to different one?在 C 中,是否可以将导出的函数名称更改为不同的名称?
【发布时间】:2012-08-23 18:30:47
【问题描述】:

全部。

我想链接一个调用malloc() 函数的库。 但是,我的目标环境是不同的 malloc() 作为内联函数提供。

我怎样才能让图书馆直接拨打malloc() 我的目标环境的malloc() 例程?

有什么办法可以改变导出的函数名吗?如果是这样的话 我可以先编码my_malloc() 并将其导出为malloc() 并链接 那个图书馆:

#include <my_environment.h>  // malloc() is inline function declared there 
void my_malloc (void) {
   malloc (void);             
}

更具体地说, 该库是来自 linux 发行版的库,因此它依赖于 libc。 但我的环境是嵌入式的,没有 libc 库,malloc(), free(), ... 是自定义实现的。有些是内联函数,有些是库函数。

【问题讨论】:

  • 您在哪个操作系统上工作?如果在 Linux 上,请了解 LD_PRELOAD
  • 我在嵌入式环境中工作。 :-(
  • 但它是嵌入式 Linux 目标操作系统吗?目标操作系统是什么?你如何链接你的程序??
  • 编辑库二进制文件,将字符序列“malloc”替换为“mylloc”?
  • 我手动将我的程序与自定义库链接,如下所示: $ ld -o a.out $(OBJS) -lmy_embedded library

标签: c linker inline static-linking


【解决方案1】:

我认为alias 属性可能会解决您的问题:

alias ("target")
    The alias attribute causes the declaration to be emitted as an alias for another symbol, which must be specified. For instance,

              void __f () { /* Do something. */; }
              void f () __attribute__ ((weak, alias ("__f")));


    defines `f' to be a weak alias for `__f'. In C++, the mangled name for the target must be used. It is an error if `__f' is not defined in the same translation unit.

    Not all target machines support this attribute.

http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html

【讨论】:

  • 也许我理解错了,但这不需要库的源代码吗?
  • @ThomasPadron-McCarthy 我以为他想将my_malloc 重命名为malloc,以便让下一个.o 使用他内联的malloc
  • 是的 user1202136。我想要那个(如果可能的话)。
【解决方案2】:

GNU 链接器 (ld) 支持 --wrap=functionname 参数。我将简单地引用手册页中的文档,因为它包含一个应该完全满足您需要的示例:

--wrap=symbol 对符号使用包装函数。任何未定义的符号引用都将解析为“__wrap_symbol”。任何对“__real_symbol”的未定义引用都将被解析为符号。

这可以用来为系统函数提供一个包装器。包装函数应称为“__wrap_symbol”。如果它想调用系统函数,它应该调用“__real_symbol”。

这是一个简单的例子:

void *
__wrap_malloc (size_t c)
{
    printf ("malloc called with %zu\n", c);
    return __real_malloc (c);
}

如果您使用--wrap malloc 将其他代码与此文件链接,则所有对“malloc”的调用将改为调用函数"__wrap_malloc。在“__wrap_malloc”中对“__real_malloc”的调用将调用真正的“malloc”函数。

您可能还希望提供“__real_malloc”函数,以便没有--wrap 选项的链接会成功。如果这样做,则不应将“__real_malloc”的定义与“__wrap_malloc”放在同一个文件中;如果你这样做了,汇编器可能会在链接器有机会将它包装到“malloc”之前解决调用。

【讨论】:

    【解决方案3】:

    怎么样:

    #define malloc my_malloc
    #include <my_environment.h>
    #undef malloc
    
    int malloc(size_t sz)
    {
       return my_malloc(sz);
    }
    
    #define malloc my_malloc
    // use your malloc here
    

    【讨论】:

      猜你喜欢
      • 2020-10-07
      • 2012-07-03
      • 1970-01-01
      • 1970-01-01
      • 2018-10-12
      • 2016-08-28
      • 2019-06-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多