【问题标题】:Forcibly link dynamic library to the global variable in the static library将动态库强制链接到静态库中的全局变量
【发布时间】:2021-07-02 17:36:13
【问题描述】:

我正在从 .make 文件生成一个带有全局字符串变量的 .c 文件,并将其编译到静态库中。 将该库链接到共享库后,缺少全局字符串符号,因为它没有在库中使用。 如何强制将该特定对象链接到动态库,或使用该字符串以便将符号添加到共享库中。

我尝试从共享库 makefile 生成另一个 .c 文件,但没有结果。 我需要将该字符串显示在共享库的 .data 部分中。

静态库的生成文件

#ifndef _teststatic
#define _teststatic
#endif

char __test_static_string[] = "This string is in static lib.";

共享库的生成文件

#ifndef _testshared
#define _testshared
#endif

char __test_shared_string[] = "This string is in shared lib.";
extern char __test_static_string[];

共享库的.data部分

Contents of section .data:
 264f20 204f2600 00000000 00000000 00000000   O&.............
 264f30 00000000 00000000 00000000 00000000  ................
 264f40 00000000 00000000 00000000 00000000  ................
 264f50 e61d1f00 00000000 f31d1f00 00000000  ................
 264f60 0a1e1f00 00000000 191e1f00 00000000  ................
 264f70 54686973 20737472 696e6720 69732069  This string is i
 264f80 6e207368 61726564 206c6962 2e00      n shared lib.. 

使用 gcc 标志

--整个存档

没有办法。

【问题讨论】:

  • 不相关,但可以保护您以后免受痛苦:What are the rules about using an underscore in a C++ identifier?
  • 嗨@mkayaalp,在这种情况下,字符串在优化过程中丢失了,但在链接过程中在我的。我试过添加 __attribute__((used)) " char test_static_string[] __attribute__((used)) = "This string is in static lib."; " 但没有帮助。
  • @NarekJaghinyan 这个怎么样:how to prevent linker from discarding a function?
  • 我已经想通了,只需要在共享库代码中使用静态库生成文件中的至少一个符号来创建对该特定对象的依赖关系。例如:void dummy_funciton(void); void dummy_funciton() { printf(test_static_string);此方法也适用于嵌套的静态库。下周我会在这个帖子中添加一个答案。

标签: c++ linux dynamic static linker


【解决方案1】:

静态库的生成文件

#ifndef _teststatic
#define _teststatic
#endif

char test_static_string[] = "This string is in static lib.";

共享库的生成文件

#ifndef _testshared
#define _testshared
#endif

#include <stdio.h>

char test_shared_string[] = "This string is in shared lib.";
extern char test_static_string[];

void dummy_function
{
    printf(test_static_string);
}

在这种情况下 printf 强制链接器链接静态库的生成文件的对象,并且所有全局字符串都出现在 shlibs .data 部分中。

此方法也适用于“嵌套”静态库。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-06
    • 2023-03-20
    相关资源
    最近更新 更多