如何引用静态库中声明的变量?

时间:2021-02-14 16:48:27

I am trying to use a modified glibc library. The glibc library is statically linked to my code. I have declared a new variable (lets call it my_libc_var) in the glibc library. However, when I try to include that variable in my program (using the extern keyword ofcourse), I get undefined reference error. How can I solve this problem?

我正在尝试使用一个修改后的glibc库。glibc库静态地链接到我的代码。我已经在glibc库中声明了一个新变量(我们称之为_mylibc_var)。但是,当我试图在程序中包含该变量时(当然是使用extern关键字),我将获得未定义的引用错误。我如何解决这个问题?

In glibc, the variable is declared as follows.

在glibc中,变量声明如下。

int my_libc_var;

whereas, in my program, it is declared as follows.

然而,在我的程序中,它被声明如下。

extern int my_libc_var;

1 个解决方案

#1


1  

Check whether in the compilation process the variable you have added is included in a source file which is compiled using options like -fvisibility=hidden or -fvisibility=internal. This will make your symbol non-referenceable from other modules.

检查在编译过程中您添加的变量是否包含在使用-fvisibility=hidden或-fvisibility=internal等选项进行编译的源文件中。这将使您的符号不能从其他模块引用。

A similar behaviour, as long as you are using gcc, is obtained using either:

类似的行为,只要您使用gcc,也可以使用:

#pragma GCC visibility push("hidden")

which can be placed at the beginning of the source file, or:

可以放置在源文件的开头,或:

int var __attribute__ ((visibility ("hidden")));

in the definition of the symbol (which clearly you didn't place, but I placed it here for completing my answer).

在符号的定义中(很明显你没有把它放在这里,但我把它放在这里是为了完成我的答案)。

For further information, you can refer to gcc attribute overview page.

有关进一步的信息,可以参考gcc属性概览页面。

#1


1  

Check whether in the compilation process the variable you have added is included in a source file which is compiled using options like -fvisibility=hidden or -fvisibility=internal. This will make your symbol non-referenceable from other modules.

检查在编译过程中您添加的变量是否包含在使用-fvisibility=hidden或-fvisibility=internal等选项进行编译的源文件中。这将使您的符号不能从其他模块引用。

A similar behaviour, as long as you are using gcc, is obtained using either:

类似的行为,只要您使用gcc,也可以使用:

#pragma GCC visibility push("hidden")

which can be placed at the beginning of the source file, or:

可以放置在源文件的开头,或:

int var __attribute__ ((visibility ("hidden")));

in the definition of the symbol (which clearly you didn't place, but I placed it here for completing my answer).

在符号的定义中(很明显你没有把它放在这里,但我把它放在这里是为了完成我的答案)。

For further information, you can refer to gcc attribute overview page.

有关进一步的信息,可以参考gcc属性概览页面。