简体   繁体   English

动态链接库中如何处理“外部”变量?

[英]How 'extern' variables are handled in dynamically linked libraries?

Recently I changed (for packaging) my own libraries to STATIC. 最近,我将自己的库(用于打包)更改为STATIC。 Now i receive error messages that a variable defined in the library is multiply defined. 现在,我收到错误消息,指出在库中定义的变量被乘以定义。 It is OK, the libraries use each other. 可以,这些库可以互相使用。 But why was this not noticed by the linker until I changed to STATIC? 但是,为什么在我更改为STATIC之前,链接器没有注意到这一点? In one of my files, I set the variable declared as 'extern' and the linker also flags it as 'multiply defined'. 在我的一个文件中,我将声明为“ extern”的变量设置为变量,链接器还将其标记为“乘以定义”。 Is it OK? 可以吗

Basically the compiler has 4 stages: 基本上,编译器有四个阶段:

pre-processing: macro and symbol edition 预处理:宏和符号版

compiling : generate assembling code to be executed by the processor 编译:生成要由处理器执行的汇编代码

assembling : generate binary code that the machine can understand(0/1 binary code) 组装:生成机器可以理解的二进制代码(0/1二进制代码)

Linking: the three previous operations are done separately for each file, however we need to edit the address mapping of each variable, pointer, function for the whole project here when we will have some problems when we have some multiple definition of variable because linking will check all file and generate an output for the whole project. 链接:前面的三个操作是针对每个文件分别完成的,但是我们需要在这里对整个项目的每个变量,指针,函数的地址映射进行编辑,如果我们在对变量有多个定义的时候会遇到一些问题,因为链接会检查所有文件并为整个项目生成输出。

if a library is declared as static then the declared and defined function inside this library can't be used until the run time but in compile time it is not allowed to use this library in other files so if it is the case we will get errors during linking stage because the compiler will figure out the use of the function inside this static library by another file which is not allowed. 如果一个库被声明为静态的,则该库中已声明和定义的函数要等到运行时才能使用,但在编译时不允许在其他文件中使用该库,因此,在这种情况下,我们会得到错误提示在链接阶段,因为编译器会找出另一个文件不允许在此静态库中使用该函数的情况。

If you want it static , then use runtime concept to use this library (for example in C you can use pointer to function . 如果您希望它是静态的,则可以使用运行时概念来使用此库(例如,在C语言中,可以使用指向函数的指针)。

But why was this not noticed by the linker until I changed to STATIC? 但是,为什么在我更改为STATIC之前,链接器没有注意到这一点?

Runtime linker allows duplicate symbol definitions (only one will be used at runtime, this is symbol interposition ). 运行时链接程序允许重复的符号定义(在运行时仅使用一个,这是符号插入 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM